Keypress not get allowed \+ to keyup?

I have the following fiddle

https://jsfiddle.net/u0bajt7m/

With keypress event allowed the \+ characters to write.

The keyup override the keypress event?

$('input').on('keypress', function() {
  $(this).val($(this).val().replace(/([^\+\d]{1})/g, ''));

}).on('keyup', function() {
  if ($(this).val($(this).val().match(/([\d]{1})+/g))) {
    $('#test').html('' + ($(this).val().length) + '').fadeIn(500, 'linear');
  }

});

result

.replace(/([^\+\d]{1})/g, '')); // not replace + and numbers.
.match(/([\d]{1})+/g))) // count only numbers but replace + character why?

This allowed to write \+ char on keypress but not work because keyup event? Why? If want to stay down the \+ characters I need to add to .match field and count it like a number.

So my question how can detect numbers only in keyup and still allow to write \+ in keypress with input.

Thanks!

Ok, first of all you need one input event, and not keyup or especially keypress.
On that one event you need to:

  1. replace value
  2. update count

Note, that user might pass data into input by pasting from clipboard, so you might wanna re-consider your regex as well

Thanks for your reply!

$('input').on('input', function() {
  $(this).val($(this).val().replace(/([^\+\d]{1})/g, ''));
  if ($(this).val($(this).val().match(/([\d]{1})+/g))) {
    $('#test').html('' + ($(this).val().length) + '').fadeIn(500, 'linear');
  }

});

This input planned just for number and a plus char I think the regexp is for that case.

Well with input event also not really wanna working. Just now not let stay and remove letters what write in input field. You write something this?

As the main problem with keypress and keyup also is not let + char to write down as keyup update and do not allow it. And no idea why :frowning:

Thanks!