clock  Mon - Sun 8.00 AM - 8.00 PM
fb
instagram
play store
pinterest

How To Allow Only Numbers To Be Typed In a Textbox Using jQuery

writter  Sumit Dey Sarkar
Date  25 Aug 2022
Language  JQuery
How To Allow Only Numbers To Be Typed In a Textbox Using jQuery

How To Allow Only Numbers To Be Typed In a Textbox Using jQuery

In this tutorial we will learn how to allow only numbers to be typed in a textbox using jQuery.

Here we will use keypress event to allow only number and also use keyCode to prevent all string values.

Let's see the Example -

How to allow only numbers to be typed in a textbox using jQuery

<!DOCTYPE html>
<html>

<head>
  <title>How to allow only numbers to be typed in a textbox using jQuery</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>

<body>

  <div class="container">
    <h1>How to allow only numbers to be typed in a textbox using jQuery</h1>

    <label>Enter Your Value</label><br>
    <input type="text" name="inputValue" class="numericinput"><br>
    <span class="errorValue" style="color: magenta; display: none">* Only allow (0 - 9) Input Digit</span>

  </div>

  <script>

    $(document).ready(function () {
      $(".numericinput").bind("keypress", function (e) {
        var keyCode = e.which ? e.which : e.keyCode

        if (!(keyCode >= 48 && keyCode <= 57)) {
          $(".errorValue").css("display", "inline");
          return false;
        } else {
          $(".errorValue").css("display", "none");
        }
      });
    });

  </script>

</body>

</html>

 

Output

jQuery