DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Only Allow Numbers In A Text Field

03.24.2009
| 20310 views |
  • submit to reddit
        Place this between the opening and closing body tag.  It has been successfully tested in Safari 4, Firefox 3, IE6, and IE7

function onlyNumbers(evt) {
	var e = evt
	if(window.event){ // IE
		var charCode = e.keyCode;
	} else if (e.which) { // Safari 4, Firefox 3.0.4
		var charCode = e.which
	}
	if (charCode > 31 && (charCode < 48 || charCode > 57))
	return false;
	return true;
}

onkeypress = "onlyNumbers(event)"