yanickrochon / jquery.uix.multiselect

Completely rewritten, multiselect widget with a more concise API
http://mind2soft.com/labs/jquery/multiselect/
MIT License
139 stars 62 forks source link

Programmatically set selected items in Multiselect #102

Closed smparsons closed 8 years ago

smparsons commented 8 years ago

I know how to programmatically de-select items, but I can't figure out how to programmatically select items.

Maybe I'm missing something really obvious, but I couldn't figure this out after looking at the documentation and messing with the DOM. Could someone help me out with this? Thanks.

yanickrochon commented 8 years ago

The widget is basically only a cosmetic sugar on top of the native element, therefore you need to perform the selection as you would normally do with a standard SELECT element. Then apply the changes to the widget. This is because there is no way to detect DOM changes from JavaScript (no standard way anyhow) so if you dynamically mainpulate your OPTIONs, then you just tell the widget to refresh itself.

$(selector).find('option:eq(2)').prop('selected', true);   // select the 3rd OPTION (0-indexed base)

$(selector).multiselect('refresh');  // update changes
smparsons commented 8 years ago

Okay, I actually tried this previously. I executed the following code in my console:

unselected = multiselect.find('option:not(:selected)');
unselected.each(function(ele) {
  $(ele).prop('selected', true);
});
multiselect.multiselect('refresh');

And I assumed the multiselect would have everything selected, but it actually didn't. However when I tried your example it selected the single option just fine. What did I do wrong in that scenario?

yanickrochon commented 8 years ago

The selector should be

// use attribute selector and apply prop to all of them
multiselect.find('option:not([selected])').prop('selected', true);
multiselect.multiselect('refresh');
smparsons commented 8 years ago

Wow. That was a simple fix. Thanks for the help, and for the great plugin.