Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options binding: select list does not reflect value of bound object

Tags:

knockout.js

I'm using the options binding on a select list used in a jQuery template:

<select data-bind="options: contactsViewModel.emailTypes, optionsText: 'Value', value: EmailType"></select>

The template is called with a knockout foreach for multiple email addresses.

EmailTypes is a list of emailtype objects The email object consist of the Value property which contains the string value of the email address, an Id property which contains a Guid id and an email type property which contains the emailtype object.

The emailtype object consists of the Value property which contains the name of the email type and a guid id.

The dropdown is correctly filled with the available email types, but the dropdown doesn't select the right item. It doesn't reflect the value of the object bound to it.

EDIT: The template with the showed select line is getting called by this: tbody data-bind="template: { name: 'emailTemplate', foreach: contactsViewModel.selectedContactEmails }">

selectedContactEmails is an observableArray filled with email objects, looking like this in Json:

{"EmailType":{"Value":"Home","Id":"191e8a64-8110-493c-b443-3063ff3a852a"},"ParentId":"191e8a64-8110-493c-b443-3063ff3a852c","Parent":null,"Value":"[email protected]","Id":"a7aae8fd-6ca3-49ae-b529-124d37a148ca"}

The properties of these objects are converted to observables using the mapping plugin.

emailTypes is an observableArray filled with EmailType objects:

{"Value":"Home","Id":"191e8a64-8110-493c-b443-3063ff3a852a"}
like image 911
RolandG Avatar asked Feb 22 '23 07:02

RolandG


1 Answers

The dropdown doesn't select the bounded value because the dropdown doesn't even know which attribute is it bounded to. You'll need to specify the selectedOptions attribute in your data binding.

The options attribute tells drop down about the array it holds.

The optionsText attribute tells drop down which property is used to display for each array item.

The optionsValue attribute tells dropdown which property is used for option value.

How will the dropdown know which value is it binded to?

Use selected options

like image 80
neebz Avatar answered May 23 '23 03:05

neebz