Skip to content
Advertisement

Update Input field value with value from a range slider using javascript

I’m trying to modify a how-to example which I got from W3Schools

The example is a range slider which display the value of the slider inside a <span> tag

What I would like to do is display the value inside an input field

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <p>Value: <span id="demo"></span></p>
</div>

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>

Source: W3Schools range slider example

I would like to display the value inside an input field instead of the <span> tag so I have tried to modify the example:

<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <input type="number" id="demo" name="fname" value="">

</div>

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo").value = slider.value;
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>

but this doesn’t work as it only display the initial value and does not update if I move the slider knob

Advertisement

Answer

You can store the element’s reference in the output var & instead of innerHTML you could just use the value attribute.

Here’s the updated code for your reference:

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.value = slider.value;

slider.oninput = function() {
  output.value = this.value;
}
<div class="slidecontainer">
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <input type="number" id="demo" name="fname" value="">
</div>
  
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement