Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  175] [ 7]  / answers: 1 / hits: 175382  / 14 Years ago, wed, december 22, 2010, 12:00:00

I have this block of code



listItems = $(#productList).find(li);

for (var li in listItems) {
var product = $(li);
var productid = product.children(.productId).val();
var productPrice = product.find(.productPrice).val();
var productMSRP = product.find(.productMSRP).val();

totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));

}


and I'm not getting the desired results - totalItems is coming out as 180+ and the rest all NaN. I suspect its where i use var product = $(li); or perhaps with the expression on the loop itself. Either way - I need to loop through the <li> items in the <ul> labelled #productList


More From » jquery

 Answers
21

You need to use .each:


var listItems = $("#productList li");
listItems.each(function(idx, li) {
var product = $(li);

// and the rest of your code
});

This is the correct way to loop through a jQuery selection.




In modern Javascript you can also use a for .. of loop:


var listItems = $("#productList li");
for (let li of listItems) {
let product = $(li);
}

Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.


[#94518] Monday, December 20, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;