3
votes

I have integrated knockout js in my project and now i am facing some issues in setting user selected values to 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 am able to load these data to dropdown and able to select the selected values using ,

selRDOBY().name

But my problem is i want to set this value back to dropdown.

Eg: From backend system i am receiving 2010 as selected Year then i need to set this value to this dropdown.

How to do this. Any help is appreciated.

1

1 Answers

0
votes

The problem here appears to be that selRDOBY is an observable rather than a regular array or an observableArray. KnockoutJS's documentation on the selectedOptions binding (which you're using to set the selected value) states:

This should be an array (or an observable array). KO sets the element’s selected options to match the contents of the array. Any previous selection state will be overwritten.

If your parameter is an observable array, the binding will update the element’s selection whenever the array changes (e.g., via push, pop or other observable array methods). If the parameter isn’t observable, it will only set the element’s selection state once and will not update it again later.

Whether or not the parameter is an observable array, KO will detect when the user selects or deselects an item in the multi-select list, and will update the array to match. This is how you can read which of the options is selected.

Because of this, you need to redeclare your selRDOBY as an observableArray.

selRDOBY: ko.observableArray([]);

You'd need to modify your existing code to ensure that this change is repsected. So any instances of selRDOBY(value) may need to be changed to selRDOBY([value]) or selRDOBY.push(value).