I have a simple code with 2 (or more) jQuery sliders:
HTML:
<label for="ST">ST:</label>
<input type="text" id="ST" value="10">
<div id="slider-ST"></div>
<label for="DX">DX:</label>
<input type="text" id="DX" value="10">
<div id="slider-DX"></div>
and JS:
$function(){
$( "#slider-ST" ).slider({
orientation: "horizontal",
range: "min",
value: 10,
slide: function (event, ui) {sliderChange(ui,"#ST");}
});
$( "#slider-DX" ).slider({
orientation: "horizontal",
range: "min",
value: 10,
slide: function (event, ui) {sliderChange(ui,"#DX");}
});
function sliderChange(t, disp)
{
$(disp).val(t.value);
};
}
It works perfectly well.
Now, I want to make it nicer and I would like to call these functions in a for loop:
$function(){
var ID_Inp = ["#slider-ST", "#slider-DX"];
var ID_Sli = ["#ST", "#DX"];
var i;
for (i=0;i<ID_Inp.length;i++)
{
$(ID_Inp[i]).slider({
orientation: "horizontal",
range: "min",
min: 1,
max: 18,
value: 10,
slide: function (event, ui) {sliderChange(ui,ID_Sli[i]);}
});
};
function sliderChange(t, disp)
{
$(disp).val(t.value);
};
}
Simplified code also available at jsfiddle:
And what happens is, that i is set to 2 after changing the slider's value and obviously function sliderChange doesn't work properly (ID_Sli[i] is undefined).
Any ideas?
I'm not sure why you'd need to use a for loop in this situation, this could be simplified. Expanding on Govind's idea, if you encapsulate the Sliders & Inputs into individual Div's:
<div id="bedsSection">
<input type="text" id="amountbeds">
<div id="slider-range-max-beds"></div>
</div>
Following this, using the same event, you could then query the parent to find the relevant input. Update accordingly.
$( "#slider-range-max-beds, #slider-range-max-cars" ).slider({
range: "max",
value: 2,
slide: function( event, ui ) {
var input = $(this).parent().find("input");
input.val( ui.value );
//Could also be written as $(this).parent().find("input").val(ui.value);
}
});