checking if number entered is a digit in jquery
Solution 1:
I would suggest using regexes:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
Or with a single regex as per @Platinum Azure's suggestion:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
Solution 2:
Forget regular expressions. JavaScript has a builtin function for this: isNaN()
:
isNaN(123) // false
isNaN(-1.23) // false
isNaN(5-2) // false
isNaN(0) // false
isNaN("100") // false
isNaN("Hello") // true
isNaN("2005/12/12") // true
Just call it like so:
if (isNaN( $("#whatever").val() )) {
// It isn't a number
} else {
// It is a number
}
Solution 3:
there is a simpler way of checking if a variable is an integer. you can use $.isNumeric() function. e.g.
$.isNumeric( 10 ); // true
this will return true but if you put a string in place of the 10, you will get false.
I hope this works for you.
Solution 4:
Following script can be used to check whether value is valid integer or not.
function myFunction() {
var a = parseInt("10000000");
if (!isNaN(a) && a <= 2147483647 && a >= -2147483647){
alert("is integer");
} else {
alert("not integer");
}
}