开发者

Make an <input type="text" /> only numbers are input-able? [duplicate]

This question already has answers here: HTML text input allow only numeric input (77 answers) Closed 8 years ago.
<input type="text" id="target" />

How to 开发者_开发问答do it with jQuery?


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.


$("#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, "");
});


$('input[type=text].someclass').blur(function(event)
{
   event.target.value = event.target.value.replace(/[^0-9]/g, "");
});


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


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜