Home > Blockchain >  Update Input field value with value from a range slider using javascript
Update Input field value with value from a range slider using javascript

Time:10-09

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 >
  <input type="range" min="1" max="100" value="50"  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 >
  <input type="range" min="1" max="100" value="50"  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

CodePudding user response:

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 >
  <input type="range" min="1" max="100" value="50"  id="myRange">
  <input type="number" id="demo" name="fname" value="">
</div>
  

CodePudding user response:

setting an onchange function on the range onchange="myfunction()"so this function will be called every time you change the slider.

inside the function setting demo.value to slider.value

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


function myfunction() {
  demo.value = slider.value
}
<div >
  <input type="range" min="1" max="100" value="50"  id="myRange" onchange="myfunction()">
  <input type="number" id="demo" name="fname" value="">

</div>

  • Related