# Allow Only Numbers in the Input Field

**URL:** <https://forum.kirupa.com/t/allow-only-numbers-in-the-input-field/294581>\
**Category:** web dev\
**Created:** [August 17, 2009, 5:40am UTC](https://forum.kirupa.com/t/allow-only-numbers-in-the-input-field/294581 "2009-08-17T05:40:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![audiohominis](https://avatars.discourse-cdn.com/v4/letter/a/c68b51/32.png) [@audiohominis](https://forum.kirupa.com/u/audiohominis)\
**Post date:** [August 17, 2009, 5:40am UTC](https://forum.kirupa.com/t/allow-only-numbers-in-the-input-field/294581/1 "2009-08-17T05:40:05Z")

</div>

Hi folx.  
I’m looking to restrict a field to numeric input.  
The following neat [example from w3schools](http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onkeydown) shows how to achieve the exact opposite of that - blocking _only_ numbers.

```auto
<html>
    <body>
        <script type="text/javascript">
            function noNumbers(e)
            {
                var keynum;
                var keychar;
                var numcheck;	
                if(window.event) // IE
                {
                    keynum = e.keyCode;
                }
                else if(e.which) // Netscape/Firefox/Opera
                {
                    keynum = e.which;
                }
                keychar = String.fromCharCode(keynum);
                numcheck = /\d/;
                return !numcheck.test(keychar);
            }
        </script>
        <form>
            Type some text (numbers not allowed):
            <input type="text" onkeydown="return noNumbers(event)" />
        </form>
    </body>
</html>

```

I found that removing the exclamation mark (!) on line #19: ([FONT=“Courier New”]return [COLOR=“Red”]![/COLOR]numcheck.test(keychar);[/FONT]) switches it to allowing only numbers. However, as a consequence, such keys as **Shift** , **Ctrl** , **Home** , **End** , **Insert** , **Delete** , **Backspace** , etc are also blocked, so some of the useful functionalities, e.g. user’s ability to Shift-select are disabled.

**Question:** How do I modify this code so the input field would accept only numbers without compromising those basic text editing functionalities or the concise elegance of the code.  
Thank you much.

PS. I never explored JavaScript before.
