0

I am trying to limit textbox input to numbers only, 0-9, without using regular expression. And, below is my code:

$("input[type='text']").on('keypress', function(e){
  if(e.which>=48 && e.which<58){
      return true;
  }else{
      return false;
  }
})
<input type="text">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

My question is: "in this case, why only keypress prevents the input of special characters?"

Mark Amery
  • 143,130
  • 81
  • 406
  • 459

1 Answers1

2

keypress doesn't return the same key codes. For example, if you add console.log(e.which) to the function and press backspace, nothing will fire. But if you press another key, it will. Also, keypress detects "shift + number" combinations as odd keycodes, so they return false in your function. For instance, "shift + 1" returns 33, but 33 should mean "page up".

keyup doesn't work because characters are rendered on keydown, therefore, keyup is too late. (You can't have a keyup event without a keydown occurring first.)

keydown doesn't prevent the special characters because these special characters require a combination of keydown/keup events (shift plus number). So the keydown returns true as soon as the number is pressed even if the shift key was held down and returned false. In order to address that you will need to map them to detect the combination as described here: Detect multiple keys on single keypress event in jQuery

Derek Story
  • 9,518
  • 1
  • 24
  • 34