Gallen Gallen - 1 year ago 63
Javascript Question

Looping through list items with jquery

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
items in the

Answer Source

You need to use .each:

var listItems = $("#productList").find("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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download