dan_vitch
dan_vitch

Reputation: 4559

Check if individual values entered by user are a number

I know how to check if the value of a field is a number, and I know how to fire an event on keyup. What I do not know how to do it check if each individual entry(keyup) by the user is a number or not. I am not interested in its e.which representation. Just if the value entered is 0-9.

I made a basic fiddle if you want to fill in the blanks.

http://jsfiddle.net/dan_vitch/M7dFy/

Upvotes: 2

Views: 1148

Answers (5)

Redacted
Redacted

Reputation: 974

Solution using a regular expression to check if the string contains all numeric characters: http://jsfiddle.net/M7dFy/13/

$('#testInput').keyup(function() {

    var message = (this.value.match(/^[0-9]+$/)) ? "I'm a number!": "I am not a number";   

    console.log(message);

});

Upvotes: 0

Samuel Liew
Samuel Liew

Reputation: 79113

$('#testInput').on('keyup', function (e) {

    if (e.keyCode >= 48 && e.keyCode <=57) {
        alert('That is a number');
    }
    else{ 
        alert('That is not a number');
    }
});

http://jsfiddle.net/M7dFy/2/

If you do not want to use the event object, you can also do this (not recommended):

$('#testInput').on('keyup', function (e) {

    var lastChar = $(this).val().charAt($(this).val().length-1);

    if (!isNaN(parseInt(lastChar))) {
        alert('That is a number');
    }
    else{ 
        alert('That is not a number');
    }
});

http://jsfiddle.net/M7dFy/7/

Upvotes: 2

ayyp
ayyp

Reputation: 6618

Hopefully this will work for you: http://jsfiddle.net/Skooljester/M7dFy/5/


$('#testInput').on('keyup', function (e) {  
    var testNum = $.isNumeric($(this).val());    
    if (testNum == true) {
        alert('That is a number');
    }
    else{ 
        alert('That is not a number');
    }
});

Upvotes: 1

bondythegreat
bondythegreat

Reputation: 1409

you can use javascript function isNaN() which return true if it's Not-a-Number

so give your if statement like this :

$('#testInput').on('keyup', function (e) {

    if (! isNaN($('#testInput').val())) {
        alert('That is a number');
    }
    else{
        alert('That is not a number');
    }
});

Upvotes: 0

Vigrond
Vigrond

Reputation: 8198

How bout something like this? http://jsfiddle.net/nUBZk/

$('#testInput').on('keyup', function (e) {

    if (Number(String.fromCharCode(e.which))) {
        console.log('That is a number');
    }
    else{ 
        console.log('That is not a number');
    }
});

If the character entered is convertable into a number, it will return true, or else NaN.

Upvotes: 0

Related Questions