Only Numbers in TextBox Using JavaScript
Submitted by donbermoy on Friday, November 27, 2015 - 11:58.
In this tutorial, we will going to create a program that inputs number only in the textbox using javascript.
Now let's start this tutorial!
1. Open Notepad++. Create a new file and name it as onlynumbers.html.
2. Create open and close tags for HTML, Title, and the Body.
3. Create a textbox that has the name and id of "numeric", with a maxlength of 12, and has a function named isNumberKey(evt) in onkeypress.
4. Now create a function named isNumberKey(evt). Have this code below:
In the code above, we have created a variable named charCode which has the event of the key code to have the keypressed event. The code (charCode > 31 && (charCode 48 || charCode > 57)) filters to input only the numbers from 1-9. Refer to this site for character coding: http://www.petefreitag.com/cheatsheets/ascii-codes/
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- <input type="text" name="numeric" id="numeric" value="" maxlength="12" onkeypress="return isNumberKey(event)" />
- <script>
- function isNumberKey(evt)
- {
- var charCode = (evt.which) ? evt.which : event.keyCode
- if (charCode > 31 && (charCode < 48 || charCode > 57)){
- return false;
- }
- return true;
- }
- </script>
Output:

Add new comment
- 46 views