Marwan Fikrat Marwan Fikrat - 23 days ago 16
HTML Question

Slider value addition picks up previous value

I have made 2 sliders that add up two numbers and outputs it in a box.

My problem is that the total box always picks up the previous value of the sliders.

Example: Both sliders are valued at 2. But the total comes out to be 3.

console.log
proved that the value output is the previous value(before slide).

I appreciate your help, thanks.

Here's a code snippet to demonstrate:



$(document).ready(function() {

$('#slider1').slider({
value: 1,
min: 1,
max: 5,
step: 1,
slide: function(event, ui) {
$("#one").val(ui.value);
$("#equals").val(add());
}
});

$('#slider2').slider({
value: 1,
min: 1,
max: 5,
step: 1,
slide: function(event, ui) {
$("#two").val(ui.value);
$("#equals").val(add());
}
});

function add() {
a = $('#slider1').slider('value');
b = $('#slider2').slider('value');
total = a + b;
return total;
}

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />

<div id="slider1"></div>
<div id="slider2"></div>
<input type="text" id="one" name="one">
<input type="text" id="two" name="two">
<input type="text" id="equals" name="equals">




Answer

In the add function you can add the values of the inputs with ids one and two to get the total sum value

$(document).ready(function(){
  
    $('#slider1').slider({
        value: 1,
        min: 1,
        max: 5,
        step: 1,
        slide: function( event, ui ){
            $("#one").val( ui.value );	
            $("#equals").val( add() );
        }
    });
  
    $('#slider2').slider({
        value: 1,
        min: 1,
        max: 5,
        step: 1,
        slide: function( event, ui ){
            $("#two").val( ui.value );	
            $("#equals").val( add() );
        }
    });
  
    function add(){
        a = $('#one').val();
        b = $('#two').val();
        if(a) a = parseInt(a);
        if(b) b = parseInt(b);
        total = a + b;
        return total;
    }  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" />

<div id="slider1"></div>
<div id="slider2"></div>
<input type="text" id="one" name="one">
<input type="text" id="two" name="two">
<input type="text" id="equals" name="equals">

Comments