This post shows you how to allow only numbers ie., (0-9) in a textbox. Often this code needed in a Registration form to avoid typing Alphabets.
You can see the demo of this script at the bottom of this post!
See the jQuery Script:
$(function() { $("#yourtextfieldid").keydown(function(event) { //allows only these keys // backspace, delete, tab, escape, and enter if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || // Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // home, end, left, right (event.keyCode >= 35 && event.keyCode <= 39)) { return; } else { // Ensure that it is a number and stop the keypress if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) { event.preventDefault(); } } }); });
Here is the usage example:
<!DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Allow Only Numbers JavaScript</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function() { $("#onlynumb").keydown(function(event) { //allows only these keys // backspace, delete, tab, escape, and enter if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || // Ctrl+A (event.keyCode == 65 && event.ctrlKey === true) || // home, end, left, right (event.keyCode >= 35 && event.keyCode <= 39)) { return; } else { // Ensure that it is a number and stop the keypress if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) { event.preventDefault(); } } }); }); </script> </head> <body> Phone: <input type="text" id="onlynumb" /> </body> </html>
Here is the demo for you: