0

I have this problem here, I want to check if the value of the input is going to be a number or not on keyup. Any help would be appreciated.

 $('input').keyup(function () {
 var check_nm = $('input').val();
 if(check_nm != "123"){
   console.log('not number');
 }else{
   console.log('is number');
 }
});

jsfiddle

7537247
  • 273
  • 4
  • 19

4 Answers4

2
$('input').keyup(function () {
  var check_nm = $('input').val();
  if (isNaN(check_nm) || check_nm.trim() == "") {
    console.log('not number');
  }else{
    console.log('is number');
   }
});

Use a combination of isNaN and.trim() == "" to ensure that blank spaces are not counted as numbers

You can also use isNaN(parseFloat(check_nm)) or $.isNumeric(a), which basically runs isNaN(parseFloat())

philz
  • 982
  • 5
  • 11
0

you can check if the number is NOT a number by calling isNaN(num) so if you want the opposite it will be !isNaN()

Steve
  • 11,116
  • 7
  • 35
  • 72
0

You can use unary operator + to convert the value to a number. And then check if it's NaN:

$('input').on('keyup', function () {
    var check_nm = +this.value;
    console.log(isNaN(check_nm) ? 'not number' : 'is number');
});

Note whitespaces and empty string will be converted to 0, so they will be considered a number. If you don't want that, see https://stackoverflow.com/a/1830844/1529630.

Community
  • 1
  • 1
Oriol
  • 249,902
  • 55
  • 405
  • 483
0

Use jQuery's $.isNumeric().

Docs @ jquery.com and cool discussion @ SO

Community
  • 1
  • 1
CmajSmith
  • 409
  • 2
  • 8