Allow only numbers in textbox in HTMl, Jquery and Plain JavaScript
HTML provides some elements that enable web applications to accept information from their users.
Text, pictures, and videos are just some of the type of information a web app may want to get from their user in order to serve a better or personalised experience.
This article focuses on how to accept numbers (phone numbers, zip codes, etc) as input.
Using the type=”number”
attribute
In HTML5, type=”number”
was added to HTML which allows users to enter a number. It automatically rejects non-numerical entries using a built-in validation. You can use it like so:
<input type=”number”>
Another benefit of this attribute is that on mobile, it shows a much friendly keypad:
It’s much easier for users to enter numbers this way than with the full keyboard.
Using JavaScript(jQuery)
Using type=”number”
is simple and it’s benefits but it does have some shortcomings. One of them is that prior to HTML5, the attribute was not there so browsers will fall back prior to that will fallback to type=”text”
. Another reason is that if you want to allow strictly integers, this would not cut it. “e”, floating-point numbers (1.3, 0.06) and negative symbols are allowed as directed by the spec. For these two reasons, we’ll use jQuery to improve the number input.
Note: Using jQuery is down to convenience than anything. The result can be achieved using plain Javascript as well.
<input type=”text” class=”number”>
We modify the markup a bit by adding a class which we would in the script section. Also, change the type value to text.
$('input.number').keyup(function (event) {
if (event.which !== 8 && event.which !== 0 && event.which < 48 || event.which > 57) {
// 0 for null value
// 8 for backspace
// 48-57 for 0-9 numbers
}
});
This code listens to the key up event which is fired after pressing a key. Since every key on the keyboard has a key code, we check to see if the code of the key pressed is not in the range of the numeric keys (48 – 57). Replace the comment with the code below.
$(this).val(function (index, value) {
return value.replace(/\D/g, "");
});
If the key entered is not in the range of numeric characters, we replace anything that’s not a digit with an empty string.
.replace()
is a method that can be used to replace a substring in a string with another string. It can be passed a string or a regular expression. In this case, we’ve opted for the latter.
\D
matches any non-digit. /\D/g
is a global search in the string to match every non-digit in the string.
Using Plain JavaScript
var input = document.querySelector('input.number');
input.addEventListener('keyup', function (event) {
if (event.which != 8 && event.which != 0 && event.which < 48 || event.which > 57) {
this.value = this.value.replace(/\D/g, "");
}
});
The full source code can be found on GitHub. A plain JavaScript version is also available if you decide to opt for the non-jQuery route.