Reputation: 7818
I have 3 sliders (they are dynamic, so I need to loop through them).
I have a jsFiddle here: http://jsfiddle.net/mtait/R5czJ/
HTML is:
<label for="slider1">item 1</label>
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0">
<label for="slider2">item 2</label>
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0">
<label for="slider3">item 3</label>
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0">
I am trying to loop through them, and create a JSON string:
function slide() {
var ExtraPrices = [20.00,30.00,50.00];
var ExtraIDs = [1,2,3];
var count = 0;
var arr = [];
$('.mtslide').each(function () {
var obj = {
id: ExtraIDs[count],
price: ExtraPrices[count],
number: $(this).slider("option", "value")
};
arr.push(obj);
count += 1;
});
alert(JSON.stringify(arr));
}
However, "number" or the value of the sliders, is always null:
How do I get the correct value of each slider, within my .each loop above?
thank you,
Mark
Upvotes: 0
Views: 2268
Reputation: 740
jQuery's each function actually gives you two variable: index and Element http://api.jquery.com/each/
Assuming you want the value of each element you want something like this:
$('.mtslide').each(function (index, Element) {
var obj = {
id: ExtraIDs[index],
price: ExtraPrices[index],
number: $(Element).val()
};
arr.push(obj);
});
Keeping a separate array for price and id can be error prone. You should consider specifying additional values on an html element with data attribute. http://html5doctor.com/html5-custom-data-attributes/ http://api.jquery.com/data/ Something like this:
<input type="range" class="mtslide" name="slider1" id="slider1" min="0" max="10" value="0" data-price="20.00" data-id="1">
<input type="range" class="mtslide" name="slider2" id="slider2" min="0" max="10" value="0" data-price="30.00" data-id="2">
<input type="range" class="mtslide" name="slider3" id="slider3" min="0" max="10" value="0" data-price="50.00" data-id="3">
Then you can call them more specifically to the element:
$('.mtslide').each(function (index, Element) {
var obj = {
id: $(Element).data("price"),
price: $(Element).data("price"),
number: $(Element).val()
};
arr.push(obj);
});
The complete fiddle: http://jsfiddle.net/Wwwtv/2/
Upvotes: 2