JavaScript Numeric Only Input

16 07 2007

Use the following JavaScript function to only allow numeric (0-9) input and backspace input in a web form text field.

JavaScript:

function numbersonly(e) {
var unicode=e.charCode? e.charCode : e.keyCode;
if (unicode!=8){ //if the key isn't the backspace key (which we should allow)
if (unicode<48||unicode>57) //if not a number return false //disable key press
}}

Usage:

<input onkeypress=”return numbersonly(event);” name=”VAT_Number”>

To allow for tabbing change (unicode!=8) to (unicode!=8 && unicode!=9)


Actions

Information

2 responses

20 11 2008
Anonymous

I’m sorry, but it doesn’t seem to work?

5 05 2009
colin

nice one,

doesn’t work in IE6 however..

Leave a comment