Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value for optionsCaption in knockoutjs

Tags:

knockout.js

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?

like image 698
gowthaman Avatar asked Aug 27 '13 12:08

gowthaman


2 Answers

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());
like image 133
Dmitry Pavlov Avatar answered Nov 10 '22 13:11

Dmitry Pavlov


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".

like image 29
Bradley Trager Avatar answered Nov 10 '22 12:11

Bradley Trager