Click to See Complete Forum and Search --> : numeric values only


rory
01-23-2003, 06:25 AM
Just wondering how you restrict an input field to only accept numeric values using java script

LAwebTek
01-23-2003, 02:42 PM
You could also try using the following function to allow numbers only in an input field.

function validate(field) {
var valid = "0123456789"
var ok = "yes";
var temp;
for (var i=0; i<field.value.length; i++) {
temp = "" + field.value.substring(i, i+1);
if (valid.indexOf(temp) == "-1") ok = "no";
}
if (ok == "no") {
alert("Invalid entry! Please enter numbers only in this field and try again.");
field.focus();
field.select();
}
}


<form>
<input type="text" name="numbers" onBlur="validate(this)">
</form>

;)

Webskater
01-23-2003, 02:57 PM
function onlynumbers()
{
if (event.keyCode < 48 || event.keyCode > 57) event.returnValue=false
}

If you call the above function like this:
<input type=text onkeypress="onlynumbers()">
the only thing a user can type into the box is the numbers 0 to 9