javascript - Using KnockoutJS, how to bind data to 2 different <select> tags from the same view model -
i have 2 select tags on view.html so
<select id="first" data-bind="options: firstdropdownoptions, optionstext: 'title', value: value"></select> <select id="second" data-bind="options: seconddropdownoptions, optionstext: 'title', value: value"></select> and in viewmodel.js
var firstdropdownoptions = ko.observablearray([ { value: -1, title: 'select type' }, { value: 111, title: 'option 1' }, { value: 222, title: 'option 2' }, { value: 333, title: 'option 3' } ]); var seconddropdownoptions = ko.observablearray([ { value: -1, title: 'select type' }, { value: 1, title: 'option new 1' }, { value: 2, title: 'option new 2' }, { value: 3, title: 'option new 3' } ]); i unable bind data both <select> tags. first <select> tag works properly. also, if move #second <select> tag before #first <select>, #second shows correct data, not #first <select>.
how bind data both <select> tags?
in both of bindings using value: value. means values of both select elements bound same model property, called value. using different arrays different objects, single value cannot function correctly. try using 2 different properties storing values, example:
var vm = { firstdropdownoptions: ko.observablearray([ { value: -1, title: 'select type' }, { value: 111, title: 'option 1' }, { value: 222, title: 'option 2' }, { value: 333, title: 'option 3' } ]), seconddropdownoptions: ko.observablearray([ { value: -1, title: 'select type' }, { value: 1, title: 'option new 1' }, { value: 2, title: 'option new 2' }, { value: 3, title: 'option new 3' } ]), // property storing selected value of firstdropdownoptions: selectedfirstoptionvalue: ko.observable(''), // property storing selected value of seconddropdownoptions: selectedsecondoptionvalue: ko.observable('') }; ko.applybindings(vm); and in html bind properties selectedfirstoptionvalue , selectedsecondoptionvalue respectively (properties contain objects arrays):
<select id="first" data-bind="options: firstdropdownoptions, optionstext: 'title', value: selectedfirstoptionvalue"></select> <select id="second" data-bind="options: seconddropdownoptions, optionstext: 'title', value: selectedsecondoptionvalue"></select> here working jsfiddle
Comments
Post a Comment