I am trying to target all input type="number"
on the page however only the first one is being fired. Does anyone knows why and how I can target all input elements?
My JS:
// Select your input element.
var numInput = document.querySelector('input');
// Listen for input event on numInput.
numInput.addEventListener('input', function(){
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false)
My jsFiddle
Use querySelectorAll to select all the elements matching selector. To select all the input type number
elements.
var allNumberInputs = document.querySelectorAll('input[type="number"]');
Updated Fiddle
Then you need to update the code that binds event on the elements. Loop over all the matched elements and bind the event on each of the element individually.
// Select your input element.
var numInput = document.querySelectorAll('input[type="number"]');
for (var i = 0, len = numInput.length; i < len; i++) {
// Listen for input event on numInput.
numInput[i].addEventListener('input', function() {
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
}, false);
}
<label for="first">First</label>
<br>
<input type="number" min="0" />
<br>
<br>
<label for="Second">Second</label>
<br>
<input type="number" min="0" />
If you have jQuery included on page
$('input[type="number"]')
Demo
$('input[type="number"]').on('input', function(e) {
// Let's match only digits.
var num = this.value.match(/^\d+$/);
if (num === null) {
// If we have no match, value will be empty.
this.value = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<label for="first">First</label>
<br>
<input type="number" min="0" />
<br>
<br>
<label for="Second">Second</label>
<br>
<input type="number" min="0" />
I'll suggest you to use HTML5 pattern attribute to allow only numeric values.
<input type="number" min="0" pattern="\d+" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With