Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach instead of options binding... how can I replicate "optionsCaption" functionality?

Tags:

knockout.js

I have been working with KnockoutJS this week and have quite a specific problem that I am hoping someone else has run into and solved before me...

Essentially I am binding up a select box but needed to be able to have control over the actual options tags themselves (disable for example) so that meant that I was unable to use the "options" binding which of course does not give you fine grained control over the options tags... here is what I came up with (it works!)

<select data-bind="foreach: $root.availableLabels, value: Label, enable: !IsConfirmed(), optionsCaption: 'Please select...'">
    <option data-bind="text: Value, value: $data, css: { 'paired-label': IsPaired }, disable: IsPaired"></option>
</select>

My issue is with the "optionsCaption", as I am using a foreach method to generate the inner options this does not automatically work like it would if I was able to use the simpler "Options" binding found on the knockout page... so if the objects I am iterating have a null "Label" value it simply displays the first one in the list as opposed to "Please Select..." which is what I would ideally like.

Does anyone know a way around this? I have not posted my view model code as I am not sure it's relevant actually but if needed of course just ask!

In short the problem is that I need to use foreach so that I can set css / attr bindings on the options however still need a "unselected" option.

Many thanks in advance for any help!

like image 269
BenjaminPaul Avatar asked Jan 10 '23 04:01

BenjaminPaul


1 Answers

You can use containerless foreachloop to generate the options after a fixed "Please select..." option:

<select data-bind="value: Label, enable: !IsConfirmed()">
    <option value="">Please select...</option>
    <!-- ko foreach: $root.availableLabels -->
    <option data-bind="text: Value, 
                       value: $data, 
                       css: { 'paired-label': IsPaired },
                       disable: IsPaired"></option>
    <!-- /ko -->
</select>

Demo: JSFiddle

like image 99
manji Avatar answered Jan 25 '23 11:01

manji