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!
You can use containerless foreach
loop 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
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