mejobloggs
mejobloggs

Reputation: 8166

Bind a <select> to an array in knockoutjs?

I have a checkbox list on a page that is bound to a knockout observableArray.

When checkboxes are selected knockout updates the observableArray as expected to something like [123, 345, 456] (if three options in that checkbox list are selected)

It then fires off a few functions that goes through the array and does a bunch of things.

My trouble is I want to be able to easily switch between using a checkbox list and a <select>. So basically single select vs multiselect, using the same ko.observable...

These extra functions don't work when it's a flat string and not an array.

When using the <select>, is there any way I can get the observable to function as a single value array?

E.g using this select...

<select data-bind="value: myObservable">

I want to make the selected value in myObservable to be:

["123"] (or [123])

instead of a plain string

"123"

Upvotes: 0

Views: 523

Answers (1)

Wayne Ellery
Wayne Ellery

Reputation: 7958

You can use the selectedOptions binding instead of value.

<select data-bind="selectedOptions: myObservable">

If you need multiple selection you can use multiple="true":

JsFiddle

Upvotes: 4

Related Questions