knockout.js - Knockoutjs Options Binding with JSON data? -
i trying list options select
tag server of knockout options binding. have php page returns json data pushed knockout observable array binded select tag. somehow not working, please refer following code reference:
html:
<div class="form-group"> <select class="form-control"> <option data-bind="options: country_names, optionstext: 'country_name'"></option> </select> </div>
javascript:
$(document).ready(function(){ function appmodel(session_info){ /* session info related bindings commented working fine */ var self = this; this.country_names = ko.observablearray(); // bindings related batch processing $(function(){ $.ajax({ url:"../api/master_list.php", type:"get", data:{mastertype: '1'}, cache:false, success:function(country_list){ ko.mapping.fromjson(country_list, {}, self.country_names); } }); }); }; $.ajax({ url:"../api/sessions.php", type:"get", data: {rqtype: '1'}, cache:false, success:function(session_info){ var data = $.parsejson(session_info); if (data.status == 'invalid_id'){ window.location.replace('../files/main.html'); } else { ko.applybindings(new appmodel(session_info)); } } }); });
sample json:
[{"country_name":"albania"},{"country_name":"chile"},{"country_name":"cuba"}]
question, why options not listed in select tag? missing obvious?
you data-binding option
element, whereas want put bindings on select
, this:
<select class="form-control" data-bind="options: country_names, optionstext: 'country_name'"> </select>
the <option...>
element gone; options generated knockout.
note the relevant documentation clear on how works. if haven't already, suggest (re-)reading it.
or, see full demo:
var data = [{"country_name":"albania"},{"country_name":"chile"},{"country_name":"cuba"}]; ko.applybindings({ country_names: data });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <select data-bind="options: country_names, optionstext: 'country_name'"></select>
Comments
Post a Comment