質問

I noticed that when I use valueAllowUnset: true with the Select2 plugin, the default value is not visible in the select box. However, when I click on the select, the correct value is highlighted.

http://jsfiddle.net/LgXcb/

Try removing ', select2: {}' from the above fiddle to see how it should work.

Any ideas on what's causing this issue? Does it have to do with the select2 custom binding function I'm using for Knockout?

役に立ちましたか?

解決

It seems that I always end up finding a solution right after setting up a bounty, even if I wait months before starting that bounty.

The problem was with the code inside the update function of my custom binding. After the observable value of the select changes, I also need to manually update select2, like so:

update: function(element, valueAccessor, allBindingsAccessor) {
  var value = ko.utils.unwrapObservable(allBindingsAccessor().value || allBindingsAccessor().selectedOptions);
  if (value) $(element).select2('val', value);
}

Working code: http://jsfiddle.net/LgXcb/5/

他のヒント

Interestingly, your setTimeout call is causing issues. Why? I'm not sure yet, but if you remove that and make a direct call to getSemesters() at the end of the function, it will select the initial value selected.

fiddle

I will keep looking at it and update you if I find the exact cause of this.


Update

It is amazing what you can find when you look at the github for the select2 plugin.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top