3

I have a solution for using an optgroup with my SELECT html tag.

Here is the SO post: Construct a knockout SELECT with optgroup based on observableArray

enter image description here

Now I would like to allow an empty value in this SELECT. I try with optionsCaption:

<select data-bind="foreach: brands, optionsCaption: '  '">
    <optgroup data-bind="attr: {label: $data}, foreach: $parent.vehicles">
    <!-- ko if: Brand == $parent -->
        <option data-bind="text: Type"></option>
    <!-- /ko -->
    </optgroup>
</select>

But it doesn't work: no empty option.

Any idea?

Thanks.

Community
  • 1
  • 1
Bronzato
  • 9,438
  • 29
  • 120
  • 212

2 Answers2

2

You can also data-bind the visibility of the caption to $index < 1 if you only want to display the caption before the first group.

<select data-bind="foreach: brands">
    <option data-bind="visible: $index() < 1">Select vehicle</option>    
        <optgroup data-bind="attr: {label: $data}, foreach: $parent.vehicles">
        <!-- ko if: Brand == $parent -->
        <option data-bind="text: Type"></option>
        <!-- /ko -->
    </optgroup>
</select>
0

You can use optionsCaption binding only in pair with options bindings. Since you don't use it you have to manually add empty option to the options list:

<select data-bind="foreach: brands">
     <option value=''>  </option>
    <optgroup data-bind="attr: {label: $data}, foreach: $parent.vehicles">
    <!-- ko if: Brand == $parent -->
        <option data-bind="text: Type"></option>
    <!-- /ko -->
    </optgroup>
</select>

Here is a working fiddle: http://jsfiddle.net/HPhmB/57/

Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47
  • I know it works in the jsfiddle but I try it in my proper application whith knockout validation and database backend and it doesn't work. I got a validation failed error when selecting this empty option. Any idea? I also try ``. – Bronzato Apr 12 '13 at 10:07
  • Maybe field you binded to the select is required therefore when you choose empty value validation is fail. – Artem Vyshniakov Apr 12 '13 at 10:13
  • No it is not required. Fields required are marked in red automatically in my page. This one is not required for sure. I also changed the value directly in the database successfully (to test). – Bronzato Apr 12 '13 at 10:21
  • Could you reproduce your issue in a fiddle? – Artem Vyshniakov Apr 12 '13 at 10:58
  • Unfortunately it does not work with my db as backend. Maybe I can publish my test project somewhere to show you? – Bronzato Apr 12 '13 at 15:55
  • THey are all blank. this seems like an invalid solution. – FlavorScape Mar 20 '14 at 19:46
  • To prevent multiple blank entries, place the option tag outside of the 'foreach: brands' loop. To do this, use after the option tag. Also, see: http://stackoverflow.com/questions/5805059/select-placeholder for proper use of the option. – brudert Jul 08 '14 at 16:42