tags:

views:

63

answers:

2

For example,to allow only digital numbers to be typed in:

<input type="text" id="target" />
+1  A: 
var value = $('#target').val();

function isNumber ( n ) { return !isNaN( n ) }

isNumber(value) // if its '3' then true
isNumber(value) // if 3 then true
isNumber(value) // if '' then false
meder
That's all?
Shore
You did nothing that actually "prevents" user input.
Shore
I simply misunderstood. Try this plugin? http://www.texotela.co.uk/code/jquery/numeric/
meder
Bad news is this plugin doesn't work if you enter CJK characters.
Shore
+3  A: 

Use the keypress() event. This example prevents characters that aren't digits (0 = 48, 9 = 57).

$(function() {
  $("#target").keypress(function(evt) {
    if (evt.which < 48 || evt.which > 57) {
      return false;
    }
  });
});

See this list of Javascript key codes.

cletus
2 issues:1.can't delete 2.can't prevent input CJK characters.
Shore
You never mentioned CJK characters for your question. Nor did you mention deleting. *sigh* common Shore question :p
meder
For the delete part, simply allow all keypresses below 48 (except 32, space). Though IMO a better solution is to simply check the entire input after each keypress like meder's answer and flag it up accordingly.
DisgruntledGoat