Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 <li> items in the <ul> labelled #productList

like image 288
Grahame A Avatar asked Dec 22 '10 17:12

Grahame A


People also ask

How do you iterate through a list in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array.

How do I iterate through a div in jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.

What is .each in jQuery?

The each() method in jQuery specifies a function that runs for every matched element. It is one of the widely used traversing methods in JQuery. Using this method, we can iterate over the DOM elements of the jQuery object and can execute a function for every matched element.


2 Answers

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.

like image 77
lonesomeday Avatar answered Sep 19 '22 03:09

lonesomeday


You can use each for this:

$('#productList li').each(function(i, li) {   var $product = $(li);     // your code goes here }); 

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

like image 28
girasquid Avatar answered Sep 20 '22 03:09

girasquid