简体   繁体   中英

How to programmatically select multiple options with Chosen.JS multiple select

I'm having trouble figuring out how to select multiple values in a multiple select programmatically, with chosenJS/chosen.js and still have the values binded to my ng-model (angularJS).

Case: I have a list of users from which some are already saved on the current project. I want to show these users as selected (but i have no idea how).

I have tried finding the indexs of the users that i want pre-selected and make them "selected" like this:

$('.chzn-container-multi').val(0).trigger('liszt:updated');
$('.chzn-container-multi').val(1).trigger('liszt:updated');
$('.chzn-container-multi').val(2).trigger('liszt:updated');

but this only selects the last one.

Any help would be much appreciated !

With help from #Marek Kowalski i was able to select the values in my list, but it wasn't applied to the ng-model connected with my dropdown, anyone have a solution to this?

Selecting multiple values and updating the chosen can be done via this one-liner

For version < 1.0

$('.chzn-container-multi').val([0,1,2]).trigger('liszt:updated');

OR for version > 1.0

$('.chzn-container-multi').val([0,1,2]).trigger('chosen:updated');

I'm not sure this is the recommended way of doing it, but the solution which works for me is to manually change the selected="selected" attributes on the options and than trigger the "liszt:updated" event. To select first 3 options use the following code:

$('select option:nth-child(1)').attr('selected', 'selected');
$('select option:nth-child(2)').attr('selected', 'selected');
$('select option:nth-child(3)').attr('selected', 'selected');
$('select').trigger('liszt:updated');
// since version 1.0 the event name is changed to
$('select').trigger('chosen:updated');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM