Allow only Numbers in Textbox using jQuery

In this post, we will explain how to allow only numbers in textbox using jQuery. We will get only number using keypress event code. Allow only numbers in textbox in need when you get valid numbers.

<!DOCTYPE html>
<html>
  <head>
      <title>Allow only numbers in jquery</title>
</head>
<body>
    
    <form action="">
        <label for="phone">Phone</label>
        <input type="text" name="phone" id="phone" placeholder="Enter phone" maxlength="10">
        <span id="phoneError"></span>
        <br><br>
        <input type="button" value="Submit" id="submitForm">
    </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>  
    $(document).ready(function() {
      $("#phone").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                $("#phoneError").html("Enter only digits").css('color','red');
                return false;
            }
        });
    });
</script>
</body>
</html>

I hope you understand allow only numbers in textbox using jQuery..

Read Also :  How to Allow only 10 Numbers in Textbox using jQuery