javascript - Using drop down selection to populate a text box with a default in KnockoutJS -
i have simple order creation form on office app i'm building. scenario cannot figure out under "order lines" section of form. want click add row row appears contains drop down containing products, 2 text boxes quantity , price. want when product selected, products price set default value in price text box, use able change still.
so far have in- can add rows, can select part- piece cannot figure out how correctly populate default price. cut down version of knockout viewmodel looks this;
viewmodel = { parts : ko.observablearray(initialdata.parts), sale : ko.observable(initialdata.sale), salelines : ko.observablearray(initialdata.salelines), addrow: function() { this.salelines.push({ id: "00000000-0000-0000-0000-000000000000", saleprice : 0.00, qty : 1, partid: "" }); $("select").combobox({ selected: function (event, ui) { $(ui.item.parentnode).change(); } }); }, removerow: function (r) { this.salelines.remove(r); } }
the sale lines rendered out through template this;
<script type="text/html" id="salelinetemplate"> <tr> <td> <select data-bind='options: viewmodel.parts, optionstext: "description", optionscaption: "select...", optionsvalue: "id", value: partid, uniquename: true' class="mustpopulatedropdown"></select> </td> <td> <input data-bind="value: qty, uniquename: true" class="required number"/> </td> <td> <input data-bind="value: saleprice, uniquename: true" class="required number"/> </td> <td> <a href="#" data-bind="click: function() { viewmodel.removerow($data) }">delete</a> </td> </tr> </script>
the actual parts collection comes backend mvc, , passed list partdto having id, description , price.
i cannot think of correct way this- figured maybe make id field of each saleline observable when create somehow make update saleprice on update, can't think how implement it?
thanks in advance help!
how this: http://jsfiddle.net/rniemeyer/vlvuc/
basically, make "value" of dropdown "selectedpart" observable set corresponding part object:
<select data-bind='options: viewmodel.parts, optionstext: "description", optionscaption: "select...", value: selectedpart, uniquename: true' class="mustpopulatedropdown"></select>
then, subscribe selectedpart changing , set saleprice based on selectedpart().price.
addrow: function() { var newrow = { id: "00000000-0000-0000-0000-000000000000", qty: ko.observable(1), saleprice: ko.observable(0), selectedpart: ko.observable() }; newrow.selectedpart.subscribe(function() { this.saleprice(this.selectedpart() ? this.selectedpart().price : 0); }, newrow);
whenever, dropdown changes on row, saleprice defaulted new selected product's price (unless pick "select..." line).
hope helps.
Comments
Post a Comment