Reputation: 13
I am new to knockout and have been playing with the Cart example here
How would I go about assigning the value of the product dropdown on each line?. I want to be able to select the value of the selected item using JQuery and retain all the cart functionality. The code that is rendered is as follows:
<td>
<select class="form-control prodName" data-bind="options: $root.sampleProducts, optionsText: "name" , optionsCaption: "Select...", value: product">
<option value="">Select...</option>
<option value="">Standard (sandwich) </option>
<option value="">Premium (lobster)</option>
<option value="">Ultimate (whole zebra)</option>
</select>
</td>
No value??... But I want:
<td>
<select class="form-control prodName" data-bind="options: $root.sampleProducts, optionsText: "name" , optionsCaption: "Select...", value: product">
<option value="">Select...</option>
<option value="1">Standard (sandwich)</option>
<option value="2">Premium (lobster)</option>
<option value="3">Ultimate (whole zebra)</option>
</select>
</td>
The values are rendered, I have used optionsValue but that just causes the cart to break..
Upvotes: 0
Views: 362
Reputation: 13
After trying about 20000 different ways, and reading through the knockout documentation may times, I ended up just adding a new column and getting setting the id value in that (not really a suitable solution but a solution never the less). If I used optionValue in any way it always broke, I did have success in updating the price field with a custom function but that in turn broke the subtotal and grandtotal functionality. The working fiddle is at this here if anyone is interested... a snip of the html is below:
<tbody data-bind='foreach: lines'>
<tr>
<td>
<select id="mySel" data-bind='options: $root.sampleProducts, optionsText: "name", optionsCaption: "Select...", value: product'> </select>
</td>
<td class='id' data-bind='with: product'>
<span data-bind='text: $parent.getId($data)'></span>
</td>
<td class='price' data-bind='with: product'>
<span data-bind='text: formatCurrency(price)'> </span>
</td>
<td class='quantity'>
<input data-bind='value: quantity, valueUpdate: "afterkeydown"' />
</td>
<td class='price'>
<input data-bind='value: formatCurrency(subtotal())' />
</td>
<td>
<a href='#' data-bind='click: $parent.removeLine'>Remove</a>
</td>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 6045
As you are adding optionsValue
to the select
which makes value
binding of dropdown to store optionsValue
instead of selected dropdown object([value,text]) which was happening prior if you are not using optionsValue .
So you need to modify viewModel accordingly
viewModel:
self.subtotal = ko.computed(function() {
return self.product() ? self.product() * parseInt("0" + self.quantity(), 10) : 0; //self.product has price
});
view:
<td class='price' data-bind='with: product'>
<span data-bind='text: formatCurrency($data)'> </span> //use $data
</td>
working sample with complete code here
Upvotes: 0