input field restricting to numbers only

Posted: Tue, Mar 22 04:14 PM (PDT)

This page shows a technique for restricting the field to just numbers. The script also allows you to automatically jump to the next field if the user presses the decimal key.

Put this JavaScript to head tag in your HTML page

<script type="text/javascript">
<!--
function numbersonly(inputfield, e, dec) {
	var key;
	var keychar;
	if (window.event)
		key = window.event.keyCode;
	else if (e)
		key = e.which;
	else
		return true;
	keychar = String.fromCharCode(key);
	if ((key == null) || (key == 0) || (key == 8) ||
		(key == 9) || (key == 13) || (key == 27))
		return true;
	else if ((("0123456789").indexOf(keychar) > -1))
		return true;
	else if (dec && (keychar == ".")) {
		inputfield.form.elements[dec].focus();
		return false;
	}
	else
		return false;
}
//-->
</script>

Now, we will use our script in HTML form

<form action="/signup" method="post">
	<label>U.S. ZIP Code:</label><input type="text" name="zip" size="5" maxlength="5" value="" onKeyPress="return numbersonly(this, event)"/>
	<button type="submit">Submit</button>
</form>
Tags: