jQuery: what is the best way to restrict “number”-

2019-01-01 04:53发布

What is the best way to restrict "number"-only input for textboxes?

I am looking for something that allows decimal points.

I see a lot of examples. But have yet to decide which one to use.

Update from Praveen Jeganathan

No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

30条回答
柔情千种
2楼-- · 2019-01-01 05:21

HTML5 supports input type number with global browser support 88%+ according to CanIUse as of Oct 2015.

<input type="number" step="0.01" min="0" name="askedPrice" id="askedPrice" />

This is not JQuery related solution, but the advantage is that on mobile phones Android keyboard will be optimized for entering numbers.

Alternatively, it is possible to use input type text with new parameter "pattern". More details in HTML5 spec.

I think it is better than jquery solution, since in this question provided jquery solution do not support thousands separator. If you can use html5.

JSFiddle: https://jsfiddle.net/p1ue8qxj/

查看更多
弹指情弦暗扣
3楼-- · 2019-01-01 05:22

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

查看更多
闭嘴吧你
4楼-- · 2019-01-01 05:24

Below is what I use to literally block the keystrokes. This only allows numbers 0-9 and a decimal point. Easy to implement, not a lot of code, and works like a charm:

<script>
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else {
        return true;
    }      
}
</script>

<input value="" onkeypress="return isNumberKey(event)">
查看更多
何处买醉
5楼-- · 2019-01-01 05:25

The numeric() plugin mentioned above, doesn't work in Opera (you can't backspace, delete or even use the back or forward keys).

The code below in both JQuery or Javascript will work perfectly (and it's only two lines).

JQuery:

$(document).ready(function() {
    $('.key-numeric').keypress(function(e) {
            var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
            if (verified) {e.preventDefault();}
    });
});

Javascript:

function isNumeric(e)
{
    var keynum = (!window.event) ? e.which : e.keyCode;
    return !((keynum == 8 || keynum == undefined || e.which == 0) ? null : String.fromCharCode(keynum).match(/[^0-9]/));
}

Of course this is for pure numeric input (plus backspace, delete, forward/back keys) only but can easily be changed to include points and minus characters.

查看更多
倾城一夜雪
6楼-- · 2019-01-01 05:25

This is a snippet I've just done (using a part of code by Peter Mortensen / Keith Bentrup) for an integer percent validation on a textfield (jQuery is required):

/* This validates that the value of the text box corresponds
 * to a percentage expressed as an integer between 1 and 100,
 * otherwise adjust the text box value for this condition is met. */
$("[id*='percent_textfield']").keyup(function(e){
    if (!isNaN(parseInt(this.value,10))) {
        this.value = parseInt(this.value);
    } else {
        this.value = 0;
    }
    this.value = this.value.replace(/[^0-9]/g, '');
    if (parseInt(this.value,10) > 100) {
        this.value = 100;
        return;
    }
});

This code:

  • Allows to use main numeric keys and numeric keypad.
  • Validates to exclude Shift-numeric chars (e.g. #, $, %, etc)
  • Replaces NaN values by 0
  • Replaces by 100 values higher than 100

I hope this helps those in need.

查看更多
只靠听说
7楼-- · 2019-01-01 05:26

Found a great solution here http://ajax911.com/numbers-numeric-field-jquery/

I just changed the "keyup" to "keydown" as per my requirement

查看更多
登录 后发表回答