1
<input type="text" id="target" />

How to do it with jQuery?

0

5 Answers 5

3

Though a bit more fragile since it uses keycodes... the following would work more intuitive because it makes it completely impossible to enter non-numbers:

$("#target").keydown(function(event) {
    return ( event.keyCode < 32 ||                             // Control characters
             ( event.keyCode >= 48 && event.keyCode <= 57 ) || // Numbers
             event.keyCode == 127 );                           // Delete key
});

Note to add: This is actually not the best way to go... since a (windows) ALT+[num]132 will make it possible to enter ä into the box. It should be combined with the keyup event to ensure that no characters have been entered as well like so, Combined:

$("#target").keydown(function(event) {
    return ( event.keyCode < 32 ||                             // Control characters
             ( event.keyCode >= 48 && event.keyCode <= 57 ) || // Numbers
             event.keyCode == 127 );                           // Delete key
});

$("#target").keyup(function(event) {
    event.target.value = event.target.value.replace(/[^0-9]/g, "");
});

Also, this doesn't work with the num-pad-numbers over here so it definately is more fragile than a simple blur() event.

Sign up to request clarification or add additional context in comments.

2 Comments

weird, it doesn't seem to work for me, it just stops everything (numbers included)
@Soufiane: As said, the keydown() / keyCodes are very fragile. See unixpapa.com/js/key.html for more information on the details.
1
$("#target").blur(function(event) {
    event.target.value = event.target.value.replace(/[^0-9]/g, "");
});

This will work as well:

$("#target").keypress(function(event) {
    event.target.value = event.target.value.replace(/[^0-9]/g, "");
});

6 Comments

I think it should be something like key up?
The problem is the {^0-9], it should be [^0-9].
@jtbandes - I must be going blind.
I can still input one letter,but only one.Why?
Use the keyup event instead of blur or keypress
|
0
$('input[type=text].someclass').blur(function(event)
{
   event.target.value = event.target.value.replace(/[^0-9]/g, "");
});

Comments

0
function onlyNumbers(evt) {
    var e = evt;
    if(window.event){ // IE
        var charCode = e.keyCode;
    } else if (e.which) { // Safari 4, Firefox 3.0.4
        var charCode = e.which;
    }
    if (charCode > 31 && (charCode < 48 || charCode > 57))
       return false;
    return true;
}

Source

Comments

-1
if (!$.browser.mozilla) {
    if (event.keyCode && (event.keyCode < 48 || event.keyCode > 57))
        event.preventDefault();
}
else {
    if (event.charCode && (event.charCode < 48 || event.charCode > 57))
        event.preventDefault();
}

1 Comment

The one who did the minus should explain why...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.