JS knockout: parameter value for dropdown?

I have an integrated js knockout in my project and now I am having to face some problems while setting user selected values ​​on Dropdown.

Code below:

<select id="regDobMonth" data-bind="options: RDOBM, optionsText: 'name', selectedOptions: selRDOBM" name="" class="date-sel month" tabindex="3"></select>

      

JS file:

RDOBY: ko.observableArray([{ name: "1986" }, { name: "1987" }, { name: "1988" }, { name: "1989" }, { name: "1990" }, { name: "1991" }, { name: "1992" }, { name: "1993" }, { name: "1994" }, { name: "1995" }, { name: "1996" }, { name: "1997" }, { name: "1998" }, { name: "1999" }, { name: "2000" }, { name: "2001" }]);

      

I can load this data into a dropdown and select the selected values ​​using

selRDOBY().name

      

But my problem is that I want to return this value in the dropdown menu.

For example: from the backend system I am getting 2010 as the selected year, then I need to set that value in this dropdown menu.

How to do it. Any help is appreciated.

+3


source to share


1 answer


The problem here is what selRDOBY

is observable

, and not a regular array or observableArray

. KnockoutJS documentation in selectedOptions

binding
(which you use to set the selected value):

It must be an array (or observable array). KO sets the selected elements according to the contents of the array. Any previous selection state will be overwritten.

If your parameter is an observable array, the binding will update the selection of items when the array changes (for example, using push, pop, or other observable array methods). If the parameter is not observable, it only sets the item selection state once and will not update it later.

Regardless of whether this parameter is an observable array, KO will detect when the user selects or deselects an item in the multi-select list and updates the array to match. This is how you can read which option is selected.

Because of this, you need to update your selRDOBY

as observableArray

.



selRDOBY: ko.observableArray([]);

      

You need to change the existing code to make sure this change is confirmed. Therefore, any instances selRDOBY(value)

may need to be changed to selRDOBY([value])

or selRDOBY.push(value)

.

0


source







All Articles