Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

javascript - HTML5 Slider with onchange function

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 seperate 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;
}

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It works, you just need to make sure that the javascript function is defined when the element is rendered, f.ex.

<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: http://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:

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

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

?http://jsfiddle.net/PPBUJ/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...