jquery keyup function check if number
Asked Answered
C

8

17

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?

Calends answered 20/6, 2013 at 8:48 Comment(3)
holds which key? Given a little bit more description of the cause of the issue?Gunas
any key... input type=text... and the user is holding for example "aaaaaaaaaaaaaaaa" so the function keyup() is not triggering until he stops holding the key "a"Calends
Thanks for providing more issue, I think my proposed solution should solve your issue.Gunas
G
38

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/

Gunas answered 20/6, 2013 at 8:56 Comment(8)
i have tried, but the new charakter is while the function keypress is running not in the textfield yet, so i cannot delet it with substr()Calends
one thing... a cannot delete numbers now :DCalends
@AdamSam You should also ignore: arrows, delete key, when text selected with mouse and block space buttonBistoury
@KevinBowersox I've a similar requirement..but in my case the user can enter a negative number also..so how to allow the user to enter "-" sign only in the first position of the numberBladdernut
@KevinBowersox Hi, it is working superbly on web but when I tried to do the same from mobile, its not working, any idea on how to make it work on mobile devicesPollinize
to allow for decimal point ... var enteredChar = String.fromCharCode(event.which); if(event.which != 8 && (isNaN(enteredChar) && enteredChar!='.') ) ....Fiendish
@Fiendish I think the decimal point check needs to be something like: event.which != 190. For me, enteredChar!='.' didn't workPhaih
What does 'event.which = 8' mean?Serapis
P
6

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;
}
Pun answered 23/6, 2015 at 14:34 Comment(0)
B
5

Try this solution:

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

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

Same questions:

Bistoury answered 20/6, 2013 at 9:3 Comment(3)
@IagoMelanias What do you mean? You are talking about second input OR about topic starter code?Bistoury
I'm talking about your code. If i use the keys at the right side of my keyboard, it doesn't work.Vasilek
@IagoMelanias Press NumLock this should fix your issue.Bistoury
L
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');

Layette answered 24/11, 2015 at 10:52 Comment(0)
J
0

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>
Jackqueline answered 29/4, 2015 at 6:26 Comment(0)
S
0

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;
    }
Savil answered 21/3, 2017 at 2:19 Comment(0)
B
0

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,'');
Burnett answered 5/9, 2017 at 17:47 Comment(0)
G
-1
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>
Geanticline answered 24/3, 2015 at 10:10 Comment(4)
this returns true for escape?Carliecarlile
That's function is wrong since it doesn't consider num pad keys, which have a different code. Please, see the alternative answer.Pun
This function return true if input is only number .Geanticline
Does not handle numpad keysSavil

© 2022 - 2024 — McMap. All rights reserved.