Knockout.js binding the disabled attribute in select tag

This example shows how to bind a select tag to viewmodel, setting the disabled attribute for each option value in the select list.


<select class="form-control" data-bind="value: frequency, event: { change: frequencySelected }">
<!-- ko foreach: {data: frequencyOptions} -->
<option data-bind="value: id, text: name, attr: { disabled: !enabled, selected: $root.frequency() === id } "></option>
<!-- /ko -->
</select>

The knockout viewmodel contains:

frequency -> a knockout observable to store the currently selected value

frequencyOptions -> a property on the viewmodel that is an array of objects in the following format:

[

{ id: 1, name: ‘second’, enabled: false },

{ id: 2, name: ‘minute’, enabled: false },

{ id: 3, name: ‘hour’, enabled: true},

{ id: 4, name: ‘day’, enabled: true}

]