How to target all inputs on the page?

This question already has an answer here:

  • jQuery same click event for multiple elements 9 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" />

    Use document.querySelectorAll() instead of document.querySelector() .

    The querySelectorAll() method returns all of the matching elements, whereas the querySelector() method only returns the first one, which is what you're getting.


    querySelector only returns one element: the first matching element.

    You can use querySelectorAll , instead. Then attach the event listener to the returned elements.

    If you also want to filter the inputs on their type, use this:

    var numInputs = document.querySelectorAll('input[type=number]');
    

    Then you can add the event listeners like this:

    for (var i = 0; i < numInputs .length; i++) {
        numInputs[i].addEventListener("click", yourFunction, false);
    }
    

    Now, since you're using jQuery, one might as well take advantage of that:

    $('body').on('input', 'input[type=number]', yourFunction);
    

    That's all you need.

    链接地址: http://www.djcxy.com/p/83442.html

    上一篇: 用Jquery选择多个选择器

    下一篇: 如何定位页面上的所有输入?