LearnFast.Ninja

JavaScript allow only numbers in text field with jQuery

Import jQuery for some. Use the ready function then find the text field by id and catch the keydown event. When the user press some keys that not a number we call event.preventDefault(). Allow only numeric (0-9) in input text. You can write console.log(event.keyCode); for find out the key code value. Allow only backspace, delete, key right and key left for more friendly use. Ensure that it is a number and stop the keypress. A number is pressed so we hide the message.

Step 1: Import jQuery for some. Use the ready function then find the text field by id and catch the keydown 
event. When the user press some keys that not a number we call event.preventDefault(). 
 
Working Example code: 

<html>

<head>

    <title>Only Numeric</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            // Allow only numeric (0-9) in input text --------------------

            $('[id$=Mock_UserID]').keydown(function (event) {

                //console.log(event.keyCode);

                // Allow only backspace, delete, key right and key left

                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37 ||

               event.keyCode == 39) {

                    // leave it empty.

                }

                else {

                    if (event.keyCode == 13) {

                        // Enter - Do post back

                    }

                        // Ensure that it is a number and stop the keypress

                    else if (event.keyCode < 48 || event.keyCode > 57) {

                        event.preventDefault();

                        // Show message to the user

                        $("[id$=ErrorDiv]").show();

                        $("[id$=ErrorDiv]").html("Type numbers only.");

                    }

                    else {

                        // A number is pressed so we hide the message

                        $("[id$=ErrorDiv]").hide();

                    }

                }

            }); // end keydown

        }); // end ready

    </script>

</head>

<body>

    <input type="text" id="Mock_UserID" />

    <br />

    <span id="ErrorDiv" class="Framework_Error_Message_Span"></span>

</body>

</html>

 
Result:


Tags

javascript

numbers text