Javascript Prompt/textbox Only Numbers
Solution 1:
here is a good number testing function I use in a bit of my code (from Validate decimal numbers in JavaScript - IsNumeric()). It will return true if number, false if not. This is floating point validation, not integer
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Solution 2:
You already have a good answer. This answer is another look at things you can do.
Assuming your number field is like the following
<input type="text" name="num_fld" id="num_fld" onchange="return chkNum();" />
and you've defined a javascript function like so
function chkNum()
{
var rc = false;
if(!isNaN(parseFloat(n)) && isFinite(n))
{
rc = true;
}
else
{
document.getElementById("num_fld").value = 0;
}
return rc;
}
This function checks to see if the number is really a number, but also monkeys with the input, so the bad value does not stay in place. Offhand I am not quite sure if returning false prevents the number from being entered (kind of like in a validate function.) I believe from my testing that returning false does affect what is in the field, but I am not 100% sure of that.
You could also alter the background and/or text color of the input field upon failure (the else part of the test, so the user notices something is wrong. alert();
is good for testing, but kind of messes up the look of your site in production.
Post a Comment for "Javascript Prompt/textbox Only Numbers"