DasBeasto
DasBeasto

Reputation: 2292

Hide first select option in Knockout dropdown

Im creating multiple dropdowns using a template like this:

    <script type="text/html" id="option-menu-template">
        <select data-bind='event: { change: myFunction( data, event) }, options:Options, optionsText:"Option",optionsValue:"ID",value: selection'></select>
    </script>
    <div data-bind="template: { name: 'option-menu-template', foreach: menuWrapper}"></div>

This adds a new dropdown:

        list.menuWrapper.push(new OptionMenu(data.DropDownOptions));

with this viewmodel

function OptionMenu(data) {
    self.myFunction = function (data, event){
        if(event.target.value && event.target.value.indexOf("|") >= 0) 
        {
            changedMenu(event.target.value);
        }
    }
    return {
        Options: ko.observableArray(data),
        selection: ko.observable()
    }
}
function KnockoutModel() {
    var self = this;
    self.menuWrapper = ko.observableArray([]);
}

var list = new KnockoutModel();
ko.applyBindings(list );

The data that comes in is always in the format:

[{"Option":"---Select a *whatever*---","ID":"0"},
{"Option":"1st Choice","ID":"1"},
{"Option":"2nd Choice","ID":"32"}]
etc.

I want the first Option "---Select a whatever---" to be the "placeholder" and just not visible in the actual dropdown. I can use this

 $('select option:nth-child(1)').attr('hidden', 'hidden');

successfully but since I create new ones I have to call that every time which is a bit cumbersome. I was wondering if there was a more Knockout way to do it?

Upvotes: 1

Views: 2442

Answers (1)

dfperry
dfperry

Reputation: 2258

See http://knockoutjs.com/documentation/options-binding.html, note 2.

the optionsAfterRender callback lets you modify options based on the backing object; the example shows how to disable options.

It may be best to keep the first option disabled rather than hiding it outright, because otherwise the first value will be automatically selected. If you keep the disabled one in the list, if there's no value pre-selected, there's still a way to make determine that the user hasn't actually selected anything (for validation purposes)

Upvotes: 2

Related Questions