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
  • 303
  • 5
  • 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
  • 1,012
  • 6
  • 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,696
  • 7
  • 43
  • 81
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
  • 274,082
  • 63
  • 437
  • 513
0

Use jQuery's $.isNumeric().

Docs @ jquery.com and cool discussion @ SO

Community
  • 1
  • 1
CmajSmith
  • 432
  • 2
  • 8