Only Numbers in TextBox Using JavaScript

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.
  1. <input type="text" name="numeric" id="numeric" value="" maxlength="12" onkeypress="return isNumberKey(event)" />
4. Now create a function named isNumberKey(evt). Have this code below:
  1. <script>
  2. function isNumberKey(evt)
  3. {
  4. var charCode = (evt.which) ? evt.which : event.keyCode
  5. if (charCode > 31 && (charCode < 48 || charCode > 57)){
  6. return false;
  7. }
  8. return true;
  9. }
  10. </script>
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 57)) filters to input only the numbers from 1-9. Refer to this site for character coding: http://www.petefreitag.com/cheatsheets/ascii-codes/

Output:

output 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

Add new comment