Home > OS >  JavaScript - add eventListener to all input with type range
JavaScript - add eventListener to all input with type range

Time:10-18

I try to achieve a functionality, that input-Elements with the type range allways parse their value to a span element which is located after the range.

Console does not output any issues, is it possible, that i can't define the type of the input in the

HTML

<div class="rowitem rowinput w100">
    <label for="person">Units</label>
    <input type="range" id="units" name="units" min="1" max="30" value="1" step="1" />
    <div class="range_sel_cont">
        <span class="range_sel">1</span>
         Units
    <div>
</div>

JS (Vanilla)

    let ranges = document.getElementsByTagName('input[type=range]');
    for (var i = 0 ; i < ranges.length; i  ) {
       ranges.addEventListener ("change", function () {
           let show = this.closest('.range_sel');
           show.innerHTML = this.value;
        });
    };

CodePudding user response:

Few things:

  • You should be adding the event listener to the item in ranges at index i, not ranges itself (which is an HTMLCollection)

  • closest() gets the closest parent element that matches the selector. The element you are trying to select inside the event listener is the child of a sibling. You can select it by getting the input's nextElementSibling.

  • There is no element with the tag input[type=range]. If you want to get all elements that match that selector, use querySelectorAll

let ranges = document.querySelectorAll('input[type=range]');
for (var i = 0; i < ranges.length; i  ) {
  ranges[i].addEventListener("change", function() {
    let show = this.nextElementSibling.querySelector('.range_sel');
    show.innerHTML = this.value;
  });
};
<div class="rowitem rowinput w100">
  <label for="person">Units</label>
  <input type="range" id="units" name="units" min="1" max="30" value="1" step="1" />
  <div class="range_sel_cont">
    <span class="range_sel">1</span> Units
    <div>
    </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related