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

AuthorSumit Dey Sarkar

Pubish Date25 Aug 2022

categoryJQuery

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

Comments 0

Leave a comment