Search code examples
javascriptjquery-selectors

querySelectorAll to get input sliders with a specific name and also value


How do I get querySelectorAll to return all sliders with name="type" and also value="0"

My current code looks like this:

function getSlider0Values(name) {
    const sliders = document.querySelectorAll(`input[name = "${name}"][value='0'] `);
    let type_0preference_list = [];
    sliders.forEach((range) => {
        type_0preference_list.push(range.id);
    });
    return type_0preference_list;
}
<div class="type_sliders">
  <label for="Apples">Apples</label>
  <input type="range" name="type" min="0" max="5" value="0" id="Apples" class="type_slider">

  <label for="Peaches">Peaches</label>
  <input type="range" name="type" min="0" max="5" value="0" id="Peaches" class="type_slider">

  <label for="Pears">Pears</label>
  <input type="range" name="type" min="0" max="5" value="0" id="Pears" class="type_slider">
</div>

It's currently selecting all sliders, not just the ones with the value 0.


Solution

  • This can be a bit confusing, because while range.value will give you the current value of the slider the test for value='0' in CSS does not get updated on input changing.

    You can update the attribute on a change and then your selecting will work. See this answer for a bit more explanation.

    One thing you can do is listen for the change event on each input and update the actual attribute accordingly. Alternatively you could just do that in your function and not bother with additional event listeners. It depends on your actual use case.

    This snippet does an update on a change by setting an event listener on each input so the value attribute is always uptodate.

    //set an event listener on each input so value attribute can be updated
    const allSliders = document.querySelectorAll('input.type_slider');
    allSliders.forEach((slider) => {
      slider.addEventListener('change', function() {
        slider.setAttribute('value', slider.value);
      });
    });
    
    function getSlider0Values(name) {
        const sliders = document.querySelectorAll(`input[name = "${name}"][value='0'] `);
        let type_0preference_list = [];
        sliders.forEach((range) => {
            type_0preference_list.push(range.id);
        });
        return type_0preference_list;
    }
    <div class="type_sliders">
      <label for="Apples">Apples</label>
      <input type="range" name="type" min="0" max="5" value="0" id="Apples" class="type_slider">
    
      <label for="Peaches">Peaches</label>
      <input type="range" name="type" min="0" max="5" value="0" id="Peaches" class="type_slider">
    
      <label for="Pears">Pears</label>
      <input type="range" name="type" min="0" max="5" value="0" id="Pears" class="type_slider">
    </div>
    <button onclick="console.log(getSlider0Values('type'))">Alter some slider(s) and then click me</button>