I have a simple textbox
in which users enter number.
Does jQuery have a isDigit
function that will allow me to show an alert box if users enter something other than digits?
The field can have decimal points as well.
The jQuery $. isNumeric() method is used to check whether the entered number is numeric or not. $. isNumeric() method: It is used to check whether the given argument is a numeric value or not.
jQuery isNumeric() method The isNumeric() method in jQuery is used to determine whether the passed argument is a numeric value or not. The isNumeric() method returns a Boolean value. If the given argument is a numeric value, the method returns true; otherwise, it returns false.
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'); ... }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With