In HTML, the input tag can be set to only take numeric inputs by setting its type property to the number or to tel. However, doing it through JavaScript is going to be a little tricky.
Step 1: The HTML Document
Create an HTML file, and in that file, set up an input field and some text telling the user to input data into the text field with the help of the following lines:
<b>Enter Numbers here</b>
<br />
<input type="text" onkeypress="return checkNumber(event)" />
</center>
In these lines:
- Input tag’s onkeypress property has been set to the return value of the checkNumber() method
- The onkeypress property is executed on a specific event happening, and this event happens to be a key press, so pass the event inside the checkNumber() method as well.
Running the HTML web page now will provide the following result on the browser:
Currently, all types of characters can be written inside this text field:
But this will change in the next section.
Step 2: Set up JavaScript code
In the JavaScript file or in the <script> tag, start by creating the function named as checkNumber():
// The upcoming lines come inside here
}
Inside this function, the first thing is to get the ASCII code of the key press by using the “event” variable:
After that, if the ASCII code is not of number, then return false to the input field otherwise, return true:
return true;
The complete code snippet will be as:
var aCode = event.which ? event.which : event.keyCode;
if (aCode > 31 && (aCode < 48 || aCode > 57)) return false;
return true;
}
With that you are done with setting up the JavaScript portion.
Step 3: Testing the Input Field
After you are done with steps 1 and step 2, simply execute the HTML document and try putting values inside the input field and observe its behavior:
It is now only allowing numbers to be written inside it and ignores other character
Conclusion
To restrict the user to only enter numeric characters inside an input using JavaScript. Then, in that case, call a function on every key pressed inside that input field, and within this function, compare the ASCII code of the key pressed against the ASCII codes of numeric values. Based on this comparison, allow the keys to be entered inside the input field.