Tuesday, 15 May 2012

javascript - How to manage child select element from within a knockout js template -



javascript - How to manage child select element from within a knockout js template -

i have next scenario, getting info server using ko.mapping , translated in form:

var viewmodel = { name: "abc", educations: [{ course: "c1", countryid: 1, cityid = 2}, { course: "c2", countryid: 2, cityid = 3}] }

i have 2 array variables, are:

var countries = [{id=1,name="uae"},{id=2,name="usa"},]; var cities = [{id=1,name="dubai", cid=1},{id=2,name="al-ain", cid=1}, {id=3,name="newyork", cid=2},{id=4,name="houston", cid=2},];

now show / edit info have next html

<div> <input type="text" data-bind="value: name"/> <table data-bind="template: { name: 'cet', foreach: educations }"> </table> </div> <script type="text/html" id="cet"> <tr> <td> <select data-bind="options: countries, optionstext: 'name', optionsvalue: 'id', optionscaption: 'select...', value: countryid"></select> </td> <td> <select data-bind="options: cities, optionstext: 'name', optionsvalue: 'id', optionscaption: 'select...', value: cityid"></select> </td> </tr> </script>

now need when info sent server, select boxes should show right items corresponding bound objects.

you've reached goal -- here working version of code.

class="lang-js prettyprint-override">var viewmodel = { name: "abc", educations: [{course: "c1", countryid: 1, cityid: 2}, {course: "c2", countryid: 2, cityid: 3}], countries: [{id: 1, name: "uae"}, {id: 2, name: "usa"}], cities: [{id: 1, name: "dubai", cid: 1}, {id: 2, name: "al-ain", cid: 1}, {id: 3, name: "newyork", cid: 2}, {id: 4, name: "houston", cid: 2}] }; ko.applybindings(viewmodel); class="lang-html prettyprint-override"><div> <input type="text" data-bind="value: name" /> <table data-bind="template: { name: 'cet', foreach: educations }"></table> </div> <script type="text/html" id="cet"> <tr> <td> <select data-bind="options: $root.countries, optionstext: 'name', optionsvalue: 'id', optionscaption: 'select...', value: countryid"></select> </td> <td> <select data-bind="options: $root.cities, optionstext: 'name', optionsvalue: 'id', optionscaption: 'select...', value: cityid"></select> </td> </tr> </script>

javascript knockout.js html-select

No comments:

Post a Comment