JavaScript Numeric Only Input

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)

5 Responses to JavaScript Numeric Only Input

  1. Anonymous says:

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

  2. colin says:

    nice one,

    doesn’t work in IE6 however..

  3. rpgivpgmr says:

    This will work.

    function numbersonly(e)
    {
    /*
    USE:
    To allow for tabbing change (unicode!=8) to (unicode!=8 && unicode!=9)
    */
    var unicode=e.charCode? e.charCode : e.keyCode;
    if (unicode!=8)
    { //if the key isn’t the backspace key (which we should allow)
    if (unicode57) //if not a number return false //disable key press
    {
    return false;
    } else {
    return true;
    }
    }
    }

  4. m says:

    add retun false to if (unicode57)
    Like below

    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 (unicode57) //if not a number return false //disable key press
    return false;}
    }

  5. Misha says:

    Hey , what is this “e” which is passed as an parameter to the function numbers only?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: