Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input field, only numbers jquery/js

I have a input field where i only wish users to type numbers

html: <input id="num" type="text" name="page" size="4" value="" />

jquery/ js:

 $("#num").keypress(function (e){
      if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
        return false;
      }
});

hope someone can help me.

btw: I'm not interesting in a larger jquery plugin to make the function work. (I have found some jquery-plugins , but there must be som other ways to fix it, with a smaller code)

like image 723
william Avatar asked Aug 14 '09 07:08

william


1 Answers

Try this:

$("#num").keypress(function (e){
  var charCode = (e.which) ? e.which : e.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
});

Values 48 through 57 represent the digits 0-9.

like image 140
Dominic Rodger Avatar answered Oct 12 '22 01:10

Dominic Rodger