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">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></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) {
            return isValid;

<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>


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