Reputation: 15455
I have 2 select elements on my web page. Is there a way to combine the select options from both select elements into 1 select element using KnockoutJS?
Given: (2 selects)
<select id="select1">
<option>One</option>
<option>Two</option>
</select>
<select id="select2">
<option>Three</option>
<option>Four</option>
</select>
Desired Result:
<select id="select1">
<option>Select 1</option> //if possible
<option>One</option>
<option>Two</option>
<option>Select 2</option> //if possible
<option>Three</option>
<option>Four</option>
</select>
Upvotes: 0
Views: 43
Reputation: 12295
In javascript:
var select1 = $('#select1'),
select2 = $('#select2'),
// create an array to bind
options = ko.observableArray();
// this value doesn't exist in the dom
options.push('Select 1');
// add the text of all children to the array
select1.children().forEach(function(i, el) {
options.push(el.innerText);
});
// this value doesn't exist in the dom
options.push('Select 2');
// add the text of all children to the array
select2.children().forEach(function(i, el) {
options.push(el.innerText);
});
// bind an options with the options property
// set to the options array to the dom
ko.applyBindings({ options: options });
In HTML:
<select data-bind="options: options"></select>
Upvotes: 1