Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  43] [ 6]  / answers: 1 / hits: 75838  / 12 Years ago, sat, december 15, 2012, 12:00:00

I have a slider (input type range) that is supposed to run a function when the value is being changed. The function should then display the new value in a separate div container. After placing an alert in the function, I know that the function isn't being called, but after googling for an hour and trying a few different methods I just can't find the error.


Here's the HTML part:


<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">

<div id="sliderAmount"></div>

JavaScript:


// Slider
function updateSlider(slideAmount)
{
alert("error");
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}

More From » html

 Answers
64

It works, you just need to make sure that the JavaScript function is defined when the element is rendered, for example:


<script>
function updateSlider(slideAmount) {
var sliderDiv = document.getElementById("sliderAmount");
sliderDiv.innerHTML = slideAmount;
}
</script>
<input id="slide" type="range" min="1" max="100" step="1" value="10" onchange="updateSlider(this.value)">
<div id="sliderAmount"></div>

See this demo: https://jsfiddle.net/Mmgxg/


A better way would be to remove the inline onchange attribute:


<input id="slide" type="range" min="1" max="100" step="1" value="10">
<div id="sliderAmount"></div>

And then add the listener in your JavaScript code:


var slide = document.getElementById('slide'),
sliderDiv = document.getElementById("sliderAmount");

slide.onchange = function() {
sliderDiv.innerHTML = this.value;
}

https://jsfiddle.net/PPBUJ/


[#81395] Friday, December 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
walker

Total Points: 726
Total Questions: 91
Total Answers: 106

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;