clock  Mon - Sun 8.00 AM - 8.00 PM
mail  edu@teknowize.com
fb
instagram
play store
pinterest

How to Allow Only Numbers in a Text Box using jQuery

  Hariom Prajapati
  24 Jun 2022
  PHP
Imperial Advance Hero Image

How to Allow Only Numbers in a Text Box using jQuery

In this tutorial we will learn how to allow only numbers in a text box using jQuery.

Here we simply disable alphabets or any special characters using jQuery.

Let’s follow below steps to allow only number in a text box using jQuery. 

 

Step 1 – Create a form with <input type="text">

<!DOCTYPE html>
<html>

<head>
    <title>Allow Only Numbers in a Text Box using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h1>How to Allow Only Numbers in a Text Box using jQuery - teknowize.com</h1>
        <input type="text" name="number" class="number" autocomplete="off">
    </div>
</body>

</html>

 

Step 2 – Add below jQuery code inside <body> tag

<script type="text/javascript">
    $('.number').keypress(function(event) {
      if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
      }
    });
</script> 

 

Let’s combine both steps to allow only number in a text box using jQuery

<!DOCTYPE html>
<html>

<head>
    <title>Allow Only Numbers in a Text Box using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

<body>
    <div class="container">
        <h1>How to Allow Only Numbers in a Text Box using jQuery - teknowize.com</h1>
        <input type="text" name="number" class="number" autocomplete="off">
    </div>
    <script type="text/javascript">
        $('.number').keypress(function(event) {
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
        });
    </script>
</body>

</html>

 

Output

jquery