jquery keyup function check if number

∥☆過路亽.° 提交于 2019-11-30 08:10:22

问题


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').keyup(function(event){
        if(isNaN(String.fromCharCode(event.which))){
            var value = $(this).val();

            $(this).val(value.substr(0,value.length-1));
        }
    });

but the problem is, whe the user holds the key with an character the function keyup is not triggering.... any ideas how i can forbid this?


回答1:


Try binding to the keypress event instead of keyup. It gets fired repeatedly when a key is held down. When the key pressed is not a number you can call preventDefault() which will keep the key from being placed in the input tag.

   $('#p_first').keypress(function(event){

       if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); //stop character from entering input
       }

   });

Working Example: http://jsfiddle.net/rTWrb/2/




回答2:


I decided to use the answer provided by @Rahul Yadav, but it is erroneous since it doesn't consider num pad keys, which have different codes.

Here, you can see a excerpt of the code table:

Here the function I implemented:

function isNumberKey(e) {
    var result = false; 
    try {
        var charCode = (e.which) ? e.which : e.keyCode;
        if ((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) {
            result = true;
        }
    }
    catch(err) {
        //console.log(err);
    }
    return result;
}



回答3:


The best way is to check value of input, instead of pressed key. Because there are tabs, arrows, backspace and other characters that need to be checked when You use character code.

That code check input value after user pressed a key:

$('#p_first').keyup(function(){
    while(! /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/.test($('#p_first').val())){
        $('#p_first').val($('#p_first').val().slice(0, -1));
    }
});

While loop remove last character until input value is valid. Regex /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/ validate integer and float number eg. "12,12", "12.1", "12.". It is important that number "12." (dot at the end) also be valid! Otherwise user can't enter any period.

And then on submit regex check for valid float number ([0-9]{1,2}) instead of ([0-9]{0,2}):

$('form').submit(function(e){
    if(! /^([0-9]+)((\.|,)([0-9]{1,2}))?$/.test($('#p_first').val())){
        $('#p_first').addClass('error');
        e.preventDefault();
    }
});

Notice: It is better to assign $('#p_first') into variable. var input = $('#p_first');




回答4:


Try this solution:

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

Demo: http://jsfiddle.net/DbRTj/

Same questions:

  • How to allow only numeric (0-9) in HTML inputbox using jQuery?
  • jQuery: what is the best way to restrict “number”-only input for textboxes? (allow decimal points)



回答5:


Try This..it may usefull.

<HTML>
<input type="text" name="qty" id="price" value="" style="width:100px;" field="Quantity" class="required">
</HTML>

<script>
 $(document).ready(function() {
$('#price').live('keyup',function(){
        this.value = this.value.replace(/[^0-9\.]/g,'');
        });
});
</script>



回答6:


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;
    }



回答7:


With a key event, use event.key to get the actual value. To check if integer:

isFinite(event.key);

An easier HTML solution would be to use the number type input. It restricts to only numbers (kind of).

<input type="number">

Either way, you should clean all user input with:

string.replace(/[^0-9]/g,'');



回答8:


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>


来源:https://stackoverflow.com/questions/17209180/jquery-keyup-function-check-if-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!