Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target all inputs on the page? [duplicate]

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

like image 245
brunodd Avatar asked Dec 24 '22 13:12

brunodd


1 Answers

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+" />
like image 174
Tushar Avatar answered Dec 27 '22 02:12

Tushar