Reputation: 6544
I've got a script setup, the loop code is here as is the html structure
https://jsfiddle.net/OwenMelbz/mPVbE/
it basically searches the non-empty id's of the li and puts them into a csv string.
however whenever i run it it always adds an extra loop in my non-fiddle version, so I have, 9 li's, 3 contain IDs, the loop runs 4 times. Why is this?
In my non-dev version it actually picks the ID of the 1st li again and adds it. for example.
1,2,3,4,5,6,1
the 1 would be on the 1st element. no idea why this is doing it?
thanks
Upvotes: 0
Views: 2133
Reputation: 47776
Here is an updated, simpler version:
$("#ingredients").submit(function(event) {
event.preventDefault(); //Just for testing so the form doesn't submit
var params = []; //Array of params
$("li").each(function() {
if ($(this).prop("id") != "") //Prop always returns a string, empty if no ID
params.push($(this).prop("id")); //Push the ID into the array
});
alert(params.join(",")); //Join the array with a coma
});
Upvotes: 3
Reputation: 30993
There is an alert outside the .each() loop in the fiddle example.
I update it: http://jsfiddle.net/IrvinDominin/mPVbE/3/
can be the same problem in your non fiddle code?
Upvotes: 1
Reputation: 15552
You have an extra alert(params);
after the .each()
in your code. That is responsible for the last alert()
.
Upvotes: 1