In this article, we will explain to you how to allow only numbers in textbox jquery on keypress. if you want to allow only numeric value in the textbox. you can use the keypress or keyup event. This is very useful for Telephone numbers, IDs, Postcodes.
You can use the new HTML5 input type ‘number’.But it is dependent on the browser that supports it or not. so sometimes we need to allow the only numbers in textbox using jquery. At the time we need this type of example. so you can see the below example.
<!DOCTYPE html> <html lang="en"> <head> <title>Allow Only Numbers In Textbox Jquery On Keypress - XpertPhp</title> <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>
Please follow and like us: