Allow only numbers to enter in the HTML input – Javascript
Today I am going to discuss the most common asked problem, allow only numbers to enter in the HTML input.
But before that let’s understand our purpose.
Why need to enter numbers only in the html input?
- If you want to show an error message on input hover or on submit the form about invalid input. You can use HTML input pattern, input type tel, number etc.
- If you want that user must not be able to enter invalid inputs. Like if you have created an input for numbers then it must accept numbers only. Then you need JavaScript solutions.
Check the codepen Demo.
Basic solutions are
Pattern attribute of HTML 5 Input
- Simple input type or using pattern attribute of HTML input
As of now HTML 5 supports regular Expression as a pattern attribute to the input field, we can use that too. But it’s not fully supported with all browsers.
<input id="patternAttr" pattern="[0-9.]+" type="text">
Or
<input id="numberType" type="number">
Input type Tel
- Even if you want that device to automatically show the keyboard according to requirements like numeric keyboard for number fields.
<input id="phoneInput" type="tel" name=”telephone_number” />
For other solutions we have to use JavaScript. That means no one can input invalid values; it will allow only numbers to enter in the HTML input.
JavaScript solutions to allow only numbers
Step 1.
Create a function where we will pass the two parameters one will be input field and another will be callback function.
This function will include all the possible events on the input field and add the JavaScript listeners for them.
This is a one time process, after this, this method will take care of everything.
function setInputFilter(textbox, inputFilter) { ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) { textbox.addEventListener(event, function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; } }); }); }
Step 2.
Now just setup the input filter for your input field. We can use this filter as many times as we want.
setInputFilter(document.getElementById("numbersOnly"), function(value) { return /^\d*\.?\d*$/.test(value); });
It is using regular Expression to allow only numbers and dots to enter in the HTML input.
Inline JavaScript to make simpler solution
Inline Js with regular Expression
We can use the oninput attribute of HTML input to listen to the changes of the field value. As the onchange event needs focus out of the input field to trigger, oninput can detect the changes while typing the data into it.
Here is the browser support for the oninput attribute.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />
Some jQuery solutions
Let’s see some basic and useful jQuery solutions to allow only digits to enter in the HTML input field. Best point is you don’t need to remember regular Expression pattern here. We are going to use the isNaN() function to identify non-numeric values.
$('body').on('propertychange input', 'input[type="text"]', function() { var inputVal = $(this).val(); if( isNaN(Number(inputVal)) ) { this.value = this.hasOwnProperty("oldValue") ? this.oldValue : ''; } else { this.oldValue = inputVal; } });
It can prevent copying non-numeric values to the input field. Allow for single decimal point and also control the drag and drop non-numeric content to this input field.
Hope you find this article useful. Please share your opinion in the comment section below.
If you have learned any other method to achieve the same, do comment below. I will add that to this list.
Let’s Learn together and grow together.