manufan22122 manufan22122 - 4 months ago 13
Javascript Question

How to pass selected option using knockout to an observable array

I am trying to pass the selected value of a drop down list to my view model using knockout js.

<select class="form-control" style="width:auto" data-bind="options: clients, optionsCaption: 'Choose...', optionsText: 'name', optionsValue: 'value', value: 'selectedCustomer'"></select>


In my view model, I have declared a ko observable to store the selected value:

self.selectedCustomer = ko.observableArray([]);


The variable is not getting populated when I select a value. Any tips? Thanks!

Answer

I can see two issues with the code:

You're binding the value to an observableArray, but the selected option would be a single customer so observable should be used instead.

The value (value: 'selectedCustomer') should also not be wrapped in single quotes because then you're effectively trying to bind to a string rather than the observable.

Try the below:

<select class="form-control" style="width:auto" data-bind="options: clients, optionsCaption: 'Choose...', optionsText: 'name', optionsValue: 'value', value: selectedCustomer"></select>

Then in the view model:

self.selectedCustomer = ko.observable();