0

I have a multi-select dropdown.I am binding a object to that .Just to get multiple values out of the selection.I am able to get the values and process it.

Here is the sample of - how i am loading the multi-select control in my page

http://jsfiddle.net/Hsakarp/d5j0zogz/

var viewModel = {
  optionValues: [{name: "name1", Id: 1, fullname: "Development"},{name: "name2", Id: 2, fullname: "Development"},{name: "name3", Id: 3, fullname: "Development"}],

    multipleSelectedOptionValues: ko.observable(),
};

But when i load the page again for edit, i want to set the values as selected values.I have tried with Jquery - JQuery multiselect - Set a value as selected in the multiselect dropdown

Can someone show me how to do it with Knockout itself?

Community
  • 1
  • 1
threeleggedrabbit
  • 1,722
  • 2
  • 28
  • 60
  • Please read the documentation first, it's all explained there. http://knockoutjs.com/documentation/selectedOptions-binding.html – Tomalak Mar 05 '15 at 08:19

1 Answers1

0

You need to set the 'optionsValue' and populate it in your observable array.

html:

<select multiple="multiple" data-bind="options: optionValues, optionsValue: 'Id', optionsText:'name', selectedOptions: multipleSelectedOptionValues"></select>

Knockout:

var viewModel = {
optionValues: [{name: "name1", Id: 1, fullname: "Development"},{name: "name2", Id: 2, fullname: "Development"},{name: "name3", Id: 3, fullname: "Development"}],

multipleSelectedOptionValues: ko.observableArray([1,3]),
};

ko.applyBindings(viewModel);

I've created an updated fiddle for you: http://jsfiddle.net/d5j0zogz/2/

As Tomalak notes, the documentation of knockout is pretty good, but can take some getting used to. It is a good idea to look through it to help your understanding of the answer.

RichL
  • 183
  • 1
  • 10
  • Thanks,I have tried this way its working ,but its blocking me from getting the entire object.Currently in the selected option am getting the entire object and i am extracting id,name,fullname from that object.I know without optionsvalue setting values is not possible.Is there any way to get the entire object ? – threeleggedrabbit Mar 05 '15 at 09:44
  • I'm not sure what you mean by 'blocking me from getting the entire object'. Could you clarify exactly what you are unable to do with the rest of the object and perhaps post some more code to show your entire viewmodel and how you are populating it from the controller? – RichL Mar 05 '15 at 10:31