Evertjan. said:
Jeff Paffett wrote on 15 sep 2006 in comp.lang.javascript:
Something like:
if (isNAN(document.getElementById('myTextField').value))
{
code if not number;
}
else
{
code if is number;
}
"Not a number"
is not the same as
"String has digits only"
Try:
if (/[^\d]/.test(document.getElementById('myTextField').value)) {
code if not number;
} else {
code if is number;
}
If you wanted to prevent anything but digits being accepted while
typing, you could attach a function to the onkeypress event of the
textfield and return false for non-digit keystrokes. This way they
wouldn't show up when typed.
There's an example of the opposite on w3schools.com. I don't know how
clean the code is, but it looks like this:
<script type="text/javascript">
function noNumbers(e)
{
var keynum
var keychar
var numcheck
if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}
keychar = String.fromCharCode(keynum)
numcheck = /\d/
return numcheck.test(keychar)
}
</script>
<form>
Type some text (numbers not allowed):
<input type="text" onkeypress="return noNumbers(event)" />
</form>
Maybe some more seasoned developers could fix any bad coding.