webGuy
webGuy

Reputation: 163

knockout JS option data-bind set select as "selected"

I have the following code and would like to set one option as "selected". Usually I use the "optionsValue" for this, but it does not seem to work here.

<select data-live-search="true" data-bind="foreach: $parent.customers, event: {change: $parent.changeWorkCustomer($data, $element.value)}">
    <option data-bind="text: customer_display_name, value: customer_id, attr: {'data-tokens': [customer_first_name(), customer_last_name(), css: { customer_fav: fav() > 0 }"></option>
</select>

Any ideas how I can set one option as selected?

Upvotes: 0

Views: 67

Answers (1)

Ray
Ray

Reputation: 3959

By binding an observable to select to hold the selected option value.

<select data-live-search="true" data-bind="foreach: $parent.customers, 
                                           event: {change: $parent.changeWorkCustomer($data, $element.value)}, 
                                           value: selectedCustomer">
    <option data-bind="text: customer_display_name, value: customer_id, attr: {'data-tokens': [customer_first_name(), customer_last_name(), css: { customer_fav: fav() > 0 }"></option>
</select>

// selects the option whose value is customerId1
this.selectedCustomer = ko.observable('customerId1'); 

Upvotes: 1

Related Questions