Question

I have a following input text field:

<p>Age: <input type="text" id="age"></p>

I need that the user should be able to type only numeric characters 0-9 in this field. How is it possible using jQuery?

2 Answers
$(document).ready(function() {
  $("#age").keydown(function(event) {
    //Allow the user to press the backspace and delete keys. If you want decimals, the key code is 190 
    if ((event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190) || 

    //Allow the user to press the Home, End, Left, Right, Down, and Up navigation keys
    (event.keyCode >= 35 && event.keyCode <= 40)) {
      //allow it, don't do anything
      return;
    }
    else {
      //Ensure that it is a number.
      //Also do not allow the user from pressing a combination of the shift and 
      //the numeric keys i.e. do not allow the user to input the !, @, #, etc. keys
      if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && 
         (event.keyCode < 96 || event.keyCode > 105)) {
        event.preventDefault(); 
      }
    }
  });
});

You can use a regular expression to test for numeric characters:

$(document).ready(function(){
  $('#age').keyup(function(e){
    if (/\D/g.test(this.value)) {
      //In the input value, replace the characters other than the digits with a blank
      this.value = this.value.replace(/\D/g, '');
    }
  });
});