views:

380

answers:

3

Hey all :)

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)

+2  A: 

Never do this. A user can update a textbox without pressing the key. He can copy paste, drag. some text.

Also this will be irritating to the user.

Just display a label nect to the filed saying that this accepts only numbers. And then

Validate your code at submission

rahul
I already do, in php..
william
Or just validate it on `blur`.
peirix
Reason for down vote??
rahul
Totally agree. Validate on submission, that is so much better. Or use one of these live validation libraries (or roll your own, ofc) that displays an error alongside with the form field. But yeah, not allowing anything but numbers in the input is totally moot.
August Lilleaas
I've downvoted because the user has asked a fairly straightforward technical question. I actually agree with your sentiment, but I don't like answers which say the question is wrong.
Dominic Rodger
I believe the effect @william is going for is here: http://demos.telerik.com/aspnet-ajax/input/examples/radnumerictextbox/firstlook/defaultcs.aspx If done properly it is unnoticeable to the user and quite effective in providing immediate feedback without having to wait for batch validation to run.
Crescent Fresh
@crescentfresh - very true, thats exactly what i'm talking about.
william
A: 

I think you forgot putting e.preventDefault(); before return.

Thinker
+4  A: 

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.

Dominic Rodger
ya, thats what i'm talking about.. it seems to work just fine! Thx you very much for your help!
william