hawkeye hawkeye - 5 months ago 40
jQuery Question

One Slider results the summation of another two Sliders using Bootstrap Slider

I am trying to update the value of Slider1 with the summation of Slider2 and Slider3, but it is only showing the value of either Slider1 or Slider2, whichever is moving. I am making some mistake in updating the value tp the Slider1.

Here is the Working Fiddle

code.html

<div class="wrapper">
<p>
Slider1
</p>
<input id="ex1" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="50" data-slider-step="1" />
<hr />
<p>
Slider2
</p>
<input id="ex2" data-slider-id='ex2Slider' type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" />
<hr />
<p>
Slider3
</p>
<input id="ex3" data-slider-id='ex3Slider' type="text" data-slider-min="0" data-slider-max="20" data-slider-step="1" />
<hr />

</div>


Javscript.js

var minSliderValue1 = $("#ex1").data("slider-min");
var maxSliderValue1 = $("#ex1").data("slider-max");
var minSliderValue2 = $("#ex2").data("slider-min");
var maxSliderValue2 = $("#ex2").data("slider-max");

$('#ex1').slider({
value : 0,
formatter: function(value) {
return 'Current value: ' + value;
}
});

$('#ex2').slider({
value : 0,
formatter: function(value) {
return 'Current value: ' + value;
}
});

$('#ex3').slider({
value : 0,
});

// If You want to change input text using slider handler
$('#ex1').on('slide', function(slider){
$("#ex3,#ex2").val(slider.value);
});

// If you want to change slider using input text
$("#ex3,#ex2").on("slide", function() {
var val = Math.abs(parseInt(this.value, 10) || (minSliderValue1+minSliderValue2));
this.value = val > (maxSliderValue1+maxSliderValue2) ? (maxSliderValue1+maxSliderValue2) : val;
$('#ex1').slider('setValue', val);
});


code.css

.wrapper {
padding : 20px;
margin-top : 20px;
}

Answer

Your issue is coming from $('#ex1').slider('setValue', val);. val is only going to contain the value of the slider currently being slid, not the sum of both of them.

Also, perhaps you want to be setting the min and max values for sliders 2 and 3, rather than 1 and 2 (if you're using 1 as the sum of the 2 and 3).

UPDATE TO INCLUDE CODE ADJUSTMENTS

All you need in the slide event listener is:

$('#ex1').slider('setValue', $('#ex2').slider('getValue') + $('#ex3').slider('getValue'));

So the updated function would be:

// If you want to change slider using input text
$("#ex3,#ex2").on("slide", function() {
    $('#ex1').slider('setValue', $('#ex2').slider('getValue') + $('#ex3').slider('getValue'));
});

http://jsfiddle.net/qng5935v/12/

Comments