Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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

>Solution :

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>
  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading