Reputation: 2199
I am using knockout options binding and select2 plugin on a select list. Initially i do not want to select any option by default instead i want to show a text something like 'Select country..' and this text should be selected initially. For this i used knockout optionsCaption binding
. It works fine, but if i apply select2 plugin on the select list the initial default text is not selected. Here my code:
HTML
<select data-bind="options: array, optionsCaption: 'All'" size="1">
</select>
JS
$('select').select2();
function VM(){
this.array =
['Afghanostan', 'Albania', 'Algeria', 'Argentina'];
}
ko.applyBindings(new VM());
I have created a JSFIDDLE also.
How to solve this issue ?
Upvotes: 1
Views: 2532
Reputation: 4539
Try this code
$('select').select2({
placeholder: "ALL"
});
<select data-bind="options: array" size="1" style="width: 200px;">
<option><option>
</select>
See this link http://jsbin.com/ivetel/19/edit
Upvotes: 1
Reputation: 9763
It has to do with the fact that "All" has a value of "". From select2's source:
initSelection: function () {
var selected;
if (this.opts.element.val() === "") {
this.close();
this.setPlaceholder();
} else {
var self = this;
this.opts.initSelection.call(null, this.opts.element, function(selected){
if (selected !== undefined && selected !== null) {
self.updateSelection(selected);
self.close();
self.setPlaceholder();
}
});
}
}
As you can see, it shortcircuits if element.val() === ''. You would need to modify the source of select2 to work with an empty-value option.
Upvotes: 0