jquery keyup function check if number

后端 未结 8 1891
南旧
南旧 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;
        }
    
    0 讨论(0)
  • 2020-12-10 03:34
    JavaScript:
    
      function isNumberKey(a){
      var x=a.val();
      a.val(x.replace(/[^0-9\.]/g,''));
    
    }
    
    HTML:
    
         <td><input type="text" name="qty" onkeypress="onkeyup="return isNumberKey($(this));"" value="" style="width:100px;" field="Quantity" class="required"></td>
    
    0 讨论(0)
提交回复
热议问题