1. The goal
Find an attribute inside a list using JavaScript, KnockoutJS or jQuery.
2. The scenario
I have a store application working with KnockoutJS to dynamize its UI.
3. The problem
Each product available to add to shopping cart of my store has an add button, but it is only available if the product isn't on shopping cart already.
I need to iterate with the shopping cart to discover if each product of my available products list is already on it.
4. A few code ago...
Each product of my available products to add to list is using this fragment to toggle between the buttons:
<!-- ko if: Summary.hasItem($element) -->
<button class="btn btn-small action remove">
<i class="icon-minus"></i>
</button>
<!-- /ko -->
<!-- ko ifnot: Summary.hasItem($element) -->
<button class="btn btn-small action add">
<i class="icon-plus"></i>
</button>
<!-- /ko -->
As you can see, I'm using the hasItem()
function to check if the product is already on the shopping cart or not — but I have to implement it, and I need your help to do this.
5. What I've already tried
As you can see below, I tried to make a loop to check product by product inside my shopping cart until...
self.hasItem = function (element) {
var $productId = $(element).closest("li").data("productid"),
products = self.products();
if (products.length > 0) {
for (var product in products) {
if (products[product].id() == $productId) {
return true;
} else {
return false;
}
}
}
};
... something went wrong! Continues in the next chapter.
6. Something goes wrong
My brain can not compute the logical, but as I have this loop for each button, it seems that when one runs, the other does not run, or if there is an item in the list, the other does not add.
7. Playground
8. I need to ask...
My loop/logic is right?