First off, check out this demo to see what I mean.
I have a basic form with a dropdown field. Initially, only one option is pre-loaded and selected. The goal is to load the remaining options when the dropdown is clicked. This functionality works fine, except for the fact that the default 'Choose' caption appears as soon as new options are loaded into the observableArray, even though the choice was saved before loading and an attempt was made to restore it.
The script looks like this:
(function() {
function CustomOption(id, name) {
this.ID = id;
this.Name = name;
}
var Options = {
List: ko.observableArray([
new CustomOption(1, "opt1")
]),
Loaded: false
}
var Choice = ko.observable(1);
function LoadOptions() {
var opts = [
new CustomOption(1, "opt1"),
new CustomOption(2, "opt2"),
new CustomOption(3, "opt3")
];
var currentChoice = Choice();
console.log("the choice from before load is " + currentChoice);
if (!Options.Loaded) {
window.setTimeout(function() {
Options.List(opts);
Options.Loaded = true;
Choice(currentChoice);
}, 100);
}
}
function ChangeOption() {
var index = 1;
if (Options.List()[index]) {
console.log("the choice id is now " + Choice());
Choice(Options.List()[index].ID);
console.log("and now it is " + Choice());
}
}
var viewModel = {
Choice: Choice,
Options: Options,
LoadOptions: LoadOptions,
ChangeOption: ChangeOption
}
ko.applyBindings(viewModel, document.getElementById("page"));
})();
This is how my view looks:
<div id = "page">
<div>
<select data-bind = "options: Options.List, optionsCaption: 'Choose', optionsText: 'Name', optionsValue: 'ID', value: Choice, click: LoadOptions"></select>
</div>
<div>your choice's id: <span data-bind = "text: Choice"></span></div>
<div>
<button type = "button" data-bind = "click: ChangeOption">Option 2 please</button>
</div>
</div>
It seems that forcing the value change actually reflects in the select field itself, which can be seen by clicking the 'change option' button.
The issue lies within the Choice(currentChoice);
line of code. It successfully changes the selection when used with a button, but not when the options are dynamically loaded.
Is there a way to maintain the selected option?
UPDATE: Upon testing in various browsers (IE, Chrome, FF), each behaves differently:
- Firefox comes closest to achieving the intended behavior,
- Chrome fails to refresh the select options list visually while it remains open, requiring it to be closed and reopened for newly loaded options to appear - a strange disconnect compared to Firefox's behavior,
- IE simply closes the select options list upon loading, which is not desirable.
Thus, the updated question is:
Can new options be appended to an open select dropdown menu across different web browsers?
Regrettably, the answer based on another example clarifies that this feature is browser-dependent and generally not possible (learn more here). Consequently, I am considering developing a custom select-like control. That concludes the discussion.