Allow only numbers in textbox jquery on keypress

If you required to add allow only numbers in textbox jquery on keypress or jquery based validation for your HTML Form textbox such as textbox should accept only numbers values on keypress event. therefor you can also use keyup or keypress event to allow only numeric values in textbox using jquery.

jquery allow only numbers on keypress Example

i will use keyCode for prevent to add data string values. i will also accept only numbers in HTML textbox using jquery.

How to allow only numeric (0-9) in HTML inputbox using jQuery?
I want to write very easy and complete example therefor you can understand how it is working this example. you can also check simple demo. i will also more example link to bottom therefor you can check it. let’ see following the complete example:

Read Also:  How to dynamically create a drop-down list with JavaScript and jQuery?

ALSO Read: JQuery Allow Only Numbers Input in Textbox

JQuery – Allow only numeric values (numbers) in Textbox

index.html

<!DOCTYPE html>
<html>
<head>
  <title>JQuery - Allow only numeric values (numbers) in Textbox - pakainfo.com</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
   
<div class="container">
  <h2>JQuery - Allow only numeric values (numbers) in Textbox - pakainfo.com</h2>
         
      <label>Please Enter Value:</label>
      <input type="text" name="myValue" class="mobile-number" >
      <span class="display-error" style="color: red; display: none">* Input digits (0 - 9)</span>
    
</div>
    
<script type="text/javascript">
    
    $(document).ready(function() {
      $(".mobile-number").bind("keypress", function (e) {
          var keyCode = e.which ? e.which : e.keyCode
               
          if (!(keyCode >= 48 && keyCode <= 57)) {
            $(".display-error").css("display", "inline");
            return false;
          }else{
            $(".display-error").css("display", "none");
          }
      });
    });
     
</script>
      
</body>
</html>

Inline: Way

<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">

Short and sweet Solution

  $('#number_only').bind('keyup paste', function(){
        this.value = this.value.replace(/[^0-9]/g, '');
  });

textbox should accept only numbers using jquery