admin管理员组

文章数量:1336613

How can you get the range slider to store output as a variable (which will then be set as a a session)

Thanks for the help

*have removed < and > so could display it with code

Below is my code (which doesn't work)

HTML Code:

    input type="range" min="1" max="100" value="50" class="slider" id="range"
    Value: span id="value" /span
    Value: span id="outputVar" /span

JavaScript Code:

    var slider = document.getElementById("range");
    var output = document.getElementById("value");
    var outputVarNo = document.getElementById("outputVar");
    output.innerHTML = slider.value;

How can you get the range slider to store output as a variable (which will then be set as a a session)

Thanks for the help

*have removed < and > so could display it with code

Below is my code (which doesn't work)

HTML Code:

    input type="range" min="1" max="100" value="50" class="slider" id="range"
    Value: span id="value" /span
    Value: span id="outputVar" /span

JavaScript Code:

    var slider = document.getElementById("range");
    var output = document.getElementById("value");
    var outputVarNo = document.getElementById("outputVar");
    output.innerHTML = slider.value;
Share edited May 1, 2019 at 18:53 Dharman 33.4k27 gold badges101 silver badges147 bronze badges asked May 1, 2019 at 18:11 Robert WhiteheadRobert Whitehead 531 silver badge4 bronze badges 2
  • 1 Why do you believe this does not work? Do you see an error? – junvar Commented May 1, 2019 at 18:20
  • 2 Code blocks allow entering full HTML. Please edit your code to reflect the actual HTML – Patrick Q Commented May 1, 2019 at 18:23
Add a ment  | 

2 Answers 2

Reset to default 4

Your example 'works' in that it does display the range value as you've described. It doesn't update the value because your JS code will execute only once at startup. To execute your code and update the output whenever the range input is changed, use an event listener:

  var slider = document.getElementById("range");
  var output = document.getElementById("value");
  var outputVarNo = document.getElementById("outputVar");

  let update = () => output.innerHTML = slider.value;

  slider.addEventListener('input', update);
  update();
<input type="range" min="1" max="100" value="50" class="slider" id="range">
Value: <span id="value"></span>
Value: <span id="outputVar"></span>

You may want to add an onChange event to your slider.

var slider = document.getElementById("range");
slider.onchange = function(event){
  var output = document.getElementById("outputVar");
  output.innerHTML = slider.value;
}

The answer provided by @junvar is better for live updates. Plus, the addEventListener is better IMO than directly using oninput

本文标签: htmlHow to get slider range value and store it in a variable within JavaScriptStack Overflow