Allow only numbers into textbox using Javascript

Hello Guys,

While building complex form, you might want users to input only numbers into textbox. HTML5 already provides input type number textbox for numbers only input box. But still you may want to user input type text because:

  • 1. You don't like up/down sign in the right side of input box.
  • 2. You don't want to increase or decrease number value by navigation button.

Well you can still use input type text and use Javascript to prevent user input other than number characters.

In this article, we will show how to use text field to input only numbers. We will use keycodes value to validate whether user input number key or text key. Based on that, we can show error message. Below condition we will use to check and prevent to input the key.

if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    return false;
}

Here is the full code with error message if user input other key instead of numeric key:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Only numbers input textbox</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="my-3">Only numbers input textbox</h1>
        <div class="row">
            <div class="col-12">
                <div class="mb-3">
                    <label for="number" class="form-label">Number</label>
                    <input type="number" class="form-control w-50" id="number" placeholder="123456">
                    <div class="alert alert-danger d-none mt-3 w-50" id="number-message">Only numbers allowed.</div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#number").keypress(function (e) {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    $('#number-message').addClass('d-block').removeClass('d-none');
                    return false;
                } else {
                    $('#number-message').addClass('d-none').removeClass('d-block');
                }
            });
        });
    </script>
</body>
</html>

This will return below view with error message.

You can check this demo example.

I hope you liked this article.

Tags:

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment