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
JavaScript
x
15
15
1
<div class="slidecontainer">
2
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
3
<p>Value: <span id="demo"></span></p>
4
</div>
5
6
<script>
7
var slider = document.getElementById("myRange");
8
var output = document.getElementById("demo");
9
output.innerHTML = slider.value;
10
11
slider.oninput = function() {
12
output.innerHTML = this.value;
13
}
14
</script>
15
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:
JavaScript
1
16
16
1
<div class="slidecontainer">
2
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
3
<input type="number" id="demo" name="fname" value="">
4
5
</div>
6
7
<script>
8
var slider = document.getElementById("myRange");
9
var output = document.getElementById("demo").value = slider.value;
10
output.innerHTML = slider.value;
11
12
slider.oninput = function() {
13
output.innerHTML = this.value;
14
}
15
</script>
16
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:
JavaScript
1
7
1
var slider = document.getElementById("myRange");
2
var output = document.getElementById("demo");
3
output.value = slider.value;
4
5
slider.oninput = function() {
6
output.value = this.value;
7
}
JavaScript
1
5
1
<div class="slidecontainer">
2
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">
3
<input type="number" id="demo" name="fname" value="">
4
</div>
5