Allow Only Numbers in Textbox

Sometimes we need the user to enter only numbers in a text field, so I have found a small piece of JavaScript that does that.

function onlyNumbers(evt){
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
}

But I wanted to take it a step further. Whatabout collecting a users telephone number. This can include other characters such as Parenthesis, the Plus Sign, Period, or space characters. Here is a list of ASCII Character Codes So heres what i came up with:

 

function onlyNumbers(evt){
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    var allowedChars="1234567890 +.()"; // List of permitted Characters
    if (allowedChars.indexOf(String.fromCharCode(charCode))<0) return false;
    return true;
}

(Yes I linked things to Wikipedia. So what of it?)

Implementing the code

On your HTML page, you will need to add the javascript inside a <script> tag. This would usually go in the <head> element.

...
    <head>
        <title>Your Title</title>
        <script type="text/javascript">
            // ....
            // Code goes Here
            // ...
        </script>
    </head>
...

Then to set your text box to only allow your selected characters you need to add an onkeypress attribute to the <input > tag

<input type="text" onkeypress="return onlyNumbers(event);" />

Here is a full sample of the code:

<html>
    <head>
        <title>Your Title</title>
        <script type="text/javascript">
            function onlyNumbers(evt){
                var e = event || evt; // for trans-browser compatibility
                var charCode = e.which || e.keyCode;
                var allowedChars="1234567890 +.()"; // List of permitted Characters
                if (allowedChars.indexOf(String.fromCharCode(charCode))<0) return false;
                return true;
            }
        </script>
    </head>�
    <body>
        Phone Number Field: <input type="text" onkeypress="return onlyNumbers(event);" />
    </body>
</html>