javascript (jquery) numeric input: keyCode for '3' and '#' are the same

前端 未结 4 1982
面向向阳花
面向向阳花 2021-01-17 23:33

I need to set up an so that it will accept only numeric chars, backspace, delete, enter, tabs and arrows.

There\'s a lot o

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 00:04

    If older browsers are'nt an issue, the number input type should cover this.

    
    

    If not you could use the isNaN javascript function

    $("#number1").on('keyup', function() {
        var myval = $(this).val();
        if (isNaN(myval)) {
            alert('numbers only!');
        }
    });
    

    Personally I would do some regex filtering with a check to see if the value has changed, that will allow any character that does not change the value, like tabs, enter and arrows. With a regex you could also add or remove any character, or you could use \d for digits only or as below, [0-9]. Up to you really what your exact needs are?

    var P;
    $("#number2").on('keyup', function() {
        var V = $(this).val();
        if (V != P) {
            $(this).val(V.replace(/[^0-9]/g,''));
        }
        P=V;
    });
    

    They could also be combined to something like this:

    $("#number3").on('keyup', function() {
        var V = $(this).val();
        if (isNaN(V)) {
            $(this).val(V.replace(/[^0-9]/g,''));
        }
    });
    

    Here's a FIDDLE to test them out!

提交回复
热议问题