javascript - Why aren't the values of the dropdowns bound? -


knockout.js great library implement mvvm.

the following minimal sample binds grid using knockout.js.

view

<div id="divdecision">   <div id="divdecisionbinding" data-bind="template: { name: 'tmpldecision' }">/div>   <script id="tmpldecision" type="text/x-jquery-tmpl">     <table id="tbldecision">       <thead>         <tr>           <th>candidate</th>           <th>decision</th>         </tr>       </thead>       <tbody data-bind="foreach:decisionlist" id="tblist">         <tr>           <td data-bind="text: candidate"></td>           <td>             <select data-bind="attr: { id: 'cmbdecision' + ':' + $index(), name: 'cmbdecision' + ':' + $index()}, options: viewmodeldecision.decisionlookup, value: 'decision', optionstext: 'decision_desc', optionscaption: 'please select'"></select>           </td>         </tr>       </tbody>     </table>   </script> </div> 

viewmodeldecision (2 members: decisionlookup , decisionlist)

decisionlookup 0 : {decision: "n", decision_desc: "no need"} 1 : {decision: "a", decision_desc: "approved"} 2 : {decision: "r", decision_desc: "rejected"} decisionlist 0 : {candidate: "000000001", decision: "a" } 1 : {candidate: "000000002", decision: "n" } 

script

var viewmodeldecision; //viewmodeldecision gets loaded web service viewmodeldecision = result; //now binding happens ko.applybindings(viewmodeldecision, document.getelementbyid("divdecision")); 

output

000000001 please select 000000002 please select 

findings

  1. the field candidate bound
  2. the options of dropdownlist cmbdecision:x bound
  3. the values of dropdownlist cmbdecision:x not bound - caption "please select" selected default.

question

why aren't values of dropdown list selected default?

the value binding should targeting observable property of viewmodel.

you meant use optionsvalue binding tell knockout use ids stored in .decision selection.

<select data-bind="options: viewmodeldecision.decisionlookup, value: selecteddecision, optionsvalue: 'decision', optionstext: 'decision_desc', optionscaption: 'please select'"></select> 

and in vm:

this.selecteddecision = ko.observable("a"); // pre-select 2nd item 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -