How to allow only numbers in textbox jquery on keypress.


You can use a new type of HTML5 input ‘number’ But it depends on the browser you support or not. so sometimes we need to allow only numbers in the text box using jquery.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript">
    $(function () {
        $("#phone").keypress(function (e) {
            var keyCode = e.keyCode || e.which;
 
            //Regex for Valid Characters i.e. Numbers.
            var regex = /^[0-9]+$/;
 
            //Validate TextBox value against the Regex.
            var isValid = regex.test(String.fromCharCode(keyCode));
            if (!isValid) {
                $("#phone_err").show();
            }
            return isValid;
        });
    });
</script>
</head>
<body>

<div class="container">
    <div class="form-group">
      <label for="phone">Phone Number:</label>
      <input type="text" class="form-control" id="phone" placeholder="Enter Phone Number" name="phone">
      <span id="phone_err" style="color: red; display:none;">Only Numbers allowed.</span>
    </div>
</div>

</body>
</html>

This input type text allows only numbers. Even other characters are entered get disappeared.