HTML/Javascript range slider

这一生的挚爱 提交于 2019-12-13 04:00:02

问题


<!DOCTYPE html>
<html>
<head>
    <script type = "text/javascript">
        $(init);

        function init(){
            $('input[type="range"]').change(getTotal());        
        }

        function getTotal(){
            var total = document.getElementById("outTotal");
            total.innerHTML = Number(slide.value) + Number(slide1.value0);
        }        

    </script>
</head>
<body>
    <input id="slide" type="range" min="1" max="100" step="1" value="10" >
    <input id="slide1" type="range" min=1 max=100 step=1 value=10 >    

    <div>
        <label>Total</label>
        <output id = "outTotal"></output>
    </div>
</body>
</html>

Here's what I have now. I'm trying to total the two range sliders and display when they are changed. I know in the HTML I can add onchange = "getTotal()", but is there a way to have the init() function running all the time. I can't figure out whats wrong with the code in that function.


回答1:


Here I've fixed it for you. Compare this with your code and spot the differences...

$(function(){
    $('input[type=range]').change(getTotal); // not () - you're not calling the function
    getTotal(); // initialy call it
});

function getTotal(){
    var total = document.getElementById("outTotal");
    var slide = document.getElementById("slide");
    var slide1 = document.getElementById("slide1");
    total.innerHTML = 1*(slide.value) + 1*(slide1.value); // here you used the slide slide1 without initializing them at all
}

Live demo http://jsfiddle.net/ox8gxk1h/




回答2:


Here you go:

$('input[type="range"]').on("change", function() {
    var total = 0;
    $('input[type="range"]').each(function() {
        number = parseInt(this.value);
        total += number;       
    });
    $("#outTotal").html(total);
});

fiddle: http://jsfiddle.net/oqpsf11f/



来源:https://stackoverflow.com/questions/26564274/html-javascript-range-slider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!