Range Slider: jQuery changes value but slider do not move

I run the following program:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title> Slider </title>
    <!-- jQuery CDN https://code.jquery.com/ -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
    <script type="text/javascript"src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $(document).ready(function() {
        console.debug("jQuery "+ (jQuery ? $().jquery : "NOT") +" loaded"); // jQuery version to console
        $('#slider1').slider({value: "11"});                                // initialize slider
        $("#slider1").slider("option", "value", 2);       
        $("#slider1" ).slider("value", 3 );
        var value = $( "#slider1" ).slider( "option", "value");    // show slider value 
        $('#sliderVal').text("Slider Value: "+value);

        $('#slider1').on('input', function(event) {                     // show slider value when changed
            var valSlider1 =  $(this).attr('id') +"   Value:" +$(this).val();
            $('#sliderVal').text(valSlider1);
        });
    });
    </script>
</head>
<body>
    <p> Slider </p> 
    <input type="range" class="sl" id="slider1"  min="0" max="100" value="99">  
    <p id="sliderVal">...</p                     //display value of slider
</body>
</html>

After running the programm the slider's "thumb" still stands on 99 The output (id=sliderVal; second last line) says: Slider Value: 3
I tried

 $('#slider1').slider({value: "11"});       
 $("#slider1").slider("option", "value", 2);       
 $("#slider1" ).slider("value", 3 );

They all change the slider's value, but the slider thumb never moves. When I move the slider's thumb with the mouse the correct values are displayed

1 answer

  • answered 2020-01-18 11:41 Pedram

    Just change val() like this $("#slider1").val(2);

    $(document).ready(function() {
      $("#slider1").val(11);
      var value = $("#slider1").val();
      $('#sliderVal').text("Slider Value: " + value);
    
      $('#slider1').on('input', function(event) { 
        var valSlider1 = $(this).attr('id') + "   Value:" + $(this).val();
        $('#sliderVal').text(valSlider1);
      });
    });
    
    $('#change').click(function() {
      $("#slider1").val(2);
      $('#sliderVal').text("Slider Value: 2");
    });
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <p> Slider </p>
    <input type="range" class="sl" id="slider1" min="0" max="100" value="99">
    <p id="sliderVal">
    </p>
    
    <button id="change">Change</button>