How do I set a value for optionsCaption in knockoutjs? For example in my application I have one select box:
<select name="item" id="item" class="input-fo" multiple="multiple" data-bind="
options : categories,
optionsValue : '_id',
optionsCaption :'Select All',
optionsText : 'name',
selectedOptions : $data['item'],
select2 : {}
">
</select>
On top of the options, I set the optionsCaption as 'Select all'. How can i set value for "select all" option when the page loads? Can anyone please give me an idea for how to do this?
You could just bind optionsCaption
to any observable property of your view model and set it to null
if you want to hide default combobox element.
Here is the example (you could try live demo as well):
HTML:
Options caption:
<input data-bind="value: defaultCaption" />
Use or not:<input type="checkbox" data-bind="checked: defaultCaptionEnabled" />
<select data-bind="
value: selected,
options: items,
optionsText: 'title',
optionsValue: 'key',
optionsCaption: dynamicOptionsCaption()">
</select>
JS:
var viewModel = function() {
var self = this;
self.selected = ko.observable('');
self.defaultCaption = ko.observable('Select ...');
self.defaultCaptionEnabled = ko.observable(true);
self.items = ko.observableArray(
[
{key: 'KEY1', title: 'One'},
{key: 'KEY2', title: 'Two'},
{key: 'KEY3', title: 'Three'},
{key: 'KEY4', title: 'Four'},
]
);
self.dynamicOptionsCaption = ko.computed(function() {
return self.defaultCaptionEnabled()
? self.defaultCaption()
: null;
});
};
ko.applyBindings(new viewModel());
If you would like "Select All" to have a value then don't use the optionsCaption binding. Instead just add an item of "Select All" as the first element of your array "MyDataSet" with an id property equal to the value you want for "Select All".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With