Iterate Over Array In Jquery
I'm trying to do some validation on a user selecting items from a list. I want to make sure an item is not added twice by checking if the is already in the array. This i
Solution 1:
You have at least three problems here:
- You aren't using
Array.forEach
correctly -- it takes a function that takes an item. - Immediately before you do your check, you're adding the item you're looking for. You will always hit the
alert
case. - You're using
checkArr
as a local variable -- you're getting an empty array each time you enter the function.
That all being said, you can accomplish your goal without keeping an array at all. I believe you can replace everything from your first alert down with this:
if ($('#' + itemtoadd, div).length == 0) {
itemtoadd = ("<li id = " + itemtoadd + " class = \"itemAdd\">" + name + "</li>");
div.append(itemtoadd);
}
else {
alert("this item has already been added");
}
Post a Comment for "Iterate Over Array In Jquery"