search

Home  >  Q&A  >  body text

Display value of HTML range slider using JS

The JS used to display the HTML range slider value works fine for the first item (A1). However, I also want to use it for A2 projects (actually there are 20 projects, so it needs to be reused 19 times). Is there a way to code for multiple iterations?

 const slideValue = document.querySelector("span");
      const inputSlider = document.querySelector("input");
      inputSlider.oninput = (()=>{
        let value = inputSlider.value;
        slideValue.textContent = value;
        slideValue.style.left = (value/.1) + "%";
        slideValue.classList.add("show");
      });
      inputSlider.onblur = (()=>{
        slideValue.classList.remove("show");
      });
<body>
<div class="itemstatement">A1. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div>

<div class="itemstatement">A2. Blah Blah Blah.</div>
<div class="range">
<div class="sliderValue"><span>0</span></div>
<div class="field">
<div class="value left">0</div>
<input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
<div class="value right">10</div>
</div></div></div></body>

P粉988025835P粉988025835466 days ago630

reply all(1)I'll reply

  • P粉680000555

    P粉6800005552023-09-13 00:49:21

    Of course. You'll easily recognize your own code, which is wrapped inside a for loop.

    var elems = document.querySelectorAll(".range");
    elems.forEach(function(elem) {
      const slideValue = elem.querySelector("span");
      const inputSlider = elem.querySelector("input");
      inputSlider.oninput = (() => {
        let value = inputSlider.value;
        slideValue.textContent = value;
        slideValue.style.left = (value / .1) + "%";
        slideValue.classList.add("show");
      });
      inputSlider.onblur = (() => {
        slideValue.classList.remove("show");
      });
    })
    <div class="itemstatement">A1. Blah Blah Blah.</div>
    <div class="range">
      <div class="sliderValue"><span>0</span></div>
      <div class="field">
        <div class="value left">0</div>
        <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1">
        <div class="value right">10</div>
      </div>
    </div>
    
    <div class="itemstatement">A2. Blah Blah Blah.</div>
    <div class="range">
      <div class="sliderValue"><span>0</span></div>
      <div class="field">
        <div class="value left">0</div>
        <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1">
        <div class="value right">10</div>
      </div>
    </div>

    reply
    0
  • Cancelreply