support@codebucket.net

How to make HTML input tag only accept numerical values by Javascript

How to make HTML input tag only accept numerical values by Javascript

K. M. Shawkat Zamil | December 20, 2022

Hello developers,

In this demonstration, I will show you how you make an HTML input tag that only accepts numerical values. There are several techniques, I will use javascript. Let's see the process.

 

As we use jQuery, which is a javascript library, we have to import jQuery from the official site (Link)

 

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

 

Next, we use a class name numeric, by that class, we can grab that input field and use our logic to accept only numerical values.

 

<input type="text" class="form-control numeric" id="test" placeholder="Enter Number">

 

In the Javascript portion, initially, we use keypress, this event occurs when users press any key on the keyboard.

 

$('.numeric').bind("keypress", function(e) 
{
    //Our Code
}

 

Then we build a logic. As we know the ASCII codes of every letter, we can accept only the number and stop any occurrence. Also, we use a class to show the error message.

 

var ret = ((keyCode >= 48 && keyCode <= 57 || keyCode == 46 || keyCode == 45) ||
    specialKeys.indexOf(keyCode) != -1);
$(".error").css("display", ret ? "none" : "inline");
return ret;

 

If we compile the logic, the script looks like the below code:

 

<script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
<script>
    $(function() {
        var specialKeys = [];
        specialKeys.push(8); //Backspace
        $(".error").css("display", "none");
        $(function() {
            $('.numeric').bind("keypress", function(e) {
                var attr_id = $(this).attr('id'); //alert(attr_id);
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57 || keyCode == 46 || keyCode == 45) ||
                    specialKeys.indexOf(keyCode) != -1);
                $(".error").css("display", ret ? "none" : "inline");
                return ret;
            });
            $('.numeric').bind("paste", function(e) {
                return false;
            });
            $(".numeric").bind("drop", function(e) {
                return false;
            });
        });
    });
</script>

 

To looks a little bit user-friendly, we use bootstrap. The complete code is given below:

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Example of erite only numeric value in input</title>
</head>

<body>
    <div class="container">
        <h2>Example of write only numeric value in input</h2>
        <div class="form-group">
            <label for="test">Enter any number</label>
            <input type="text" class="form-control numeric" id="test" placeholder="Enter Number">
            <small id="text" class="form-text text-muted error">In the input box you cannot write alphabet</small>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
<script>
    $(function() {
        var specialKeys = [];
        specialKeys.push(8); //Backspace
        $(".error").css("display", "none");
        $(function() {
            $('.numeric').bind("keypress", function(e) {
                var attr_id = $(this).attr('id'); //alert(attr_id);
                var keyCode = e.which ? e.which : e.keyCode
                var ret = ((keyCode >= 48 && keyCode <= 57 || keyCode == 46 || keyCode == 45) ||
                    specialKeys.indexOf(keyCode) != -1);
                $(".error").css("display", ret ? "none" : "inline");
                return ret;
            });
            $('.numeric').bind("paste", function(e) {
                return false;
            });
            $(".numeric").bind("drop", function(e) {
                return false;
            });
        });
    });
</script>
</body>

</html>

 

If we run the above code the output looks like this:

 

Read More: Calculate years months days between two dates in JavaScript

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.