jquery keyup function check if number

后端 未结 8 1906
南旧
南旧 2020-12-10 02:59

i am trying to create an input field where the user can only type in numbers. this function is already working almost fine for me:

        $(\'#p_first\').k         


        
8条回答
  •  一个人的身影
    2020-12-10 03:34

    I used the following function to check if a given string is number or not. This implementation works on keyup and keydown and also takes care of numpad keys

    // Validate Numeric inputs
    function isNumber(o) {
        return o == '' || !isNaN(o - 0);
    }
    

    Assuming that your key code on the keyup or keydown event is in keyCode variable:

    var keyCode = e.keyCode || e.which;
    if (keyCode >= 96 && keyCode <= 105) {
            // Numpad keys
            keyCode -= 48;
    }
    console.log(isNumber(String.fromCharCode(keyCode)));
    console.log(isNumber($(this).val() + String.fromCharCode(keyCode)));
    

    Return false if the return value from isNumber is false:

        var txtVal = $(this).val() + String.fromCharCode(keyCode);
        if (!isNumber(txtVal)) {
            e.returnValue = false;
        }
    

提交回复
热议问题