In javascript how to check for a textbox to allow only numbers to be typed and not to allow characters and special characters like ' " etc...
Printable View
In javascript how to check for a textbox to allow only numbers to be typed and not to allow characters and special characters like ' " etc...
all single digit (pos, real) numbers are either greater than or equal to zero, or less than or equal to 9. So just run through the string and look for something that doesn't fit this description.
Code:
for (i=0; i<passedValue.length; i++) {
if (passedVal.charAt(i) < "0") { return false}
if (passedVal.charAt(i) > "9") { return false}
}
or like this:
Code:
<HTML>
<HEAD>
<script Language="JavaScript">
function check(contents)
{
if (((contents / contents) != 1) && (contents != 0))
{
alert('Please enter only numbers into this text box')
}
}
</script>
</HEAD>
<BODY>
<input name="txt1" onBlur="check(this.value)">
</BODY>
</HTML>
Or you could be really flash and use regular expressions to do it:-
Code:
<HTML>
<HEAD>
<script Language="JavaScript">
function check(contents)
{
var pattern = /[0-9]/;
flag = pattern.test(contents);
if (!flag) {
alert('Please enter only numbers into this text box')
}
}
</script>
</HEAD>
<BODY>
<input name="txt1" onBlur="check(this.value)">
</BODY>
</HTML>