Reputation: 2144
I have an observable array "products" that includes products objects and the products objects are printed with the foreach
binding. What I want is to insert an input box next to each product row, together with an add to cart button so the user can select quantity for each product and all this information to be added to the cart. How can I achieve this ?
Please help, I'm a newbie in knockout.js. Fiddle here: http://jsfiddle.net/PGh6y/1/
Upvotes: 1
Views: 382
Reputation: 139758
You need to add a quantity
observable property to your Product object:
var Product = function (id, name, price)
{
this.id = id;
this.name = name;
this.price = price;
this.quantity = ko.observable(1);
};
Then you need to use the value
binding on your input to be able to edit the quantity
:
<input id="quantity" type="number" min="1" data-bind="value: quantity" />
Finally in your addToCart
you can get the current item as the first parameter of the method so you just need to create a new orderedItem
and push into your orderedItems
collections:
self.addToCart = function (product) {
self.orderedItems.push(
new orderedItem(product.id, product.name, product.price, product.quantity()));
};
Demo JSFiddle.
Note: I've also fixed the removeFromCart
and the wrong property names in the second table.
Upvotes: 2