Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select multiple options dynamically in chosen select

I am using jquery chosen select on the html page where the user could select multiple options and save the record. I need to present an update page to the user and am trying to have the multi select chosen drop down preselected with the stored options. For a single select chosen this can be done by triggering the update as follows:

 $('#ns_StatusClass').val(2);
 $('#ns_StatusClass').trigger("chosen:updated");

But I am not able to figure out how to accomplish it with multi select chosen. I tried to trigger the update after selecting the values like:

for(var i=0; i< $PAGE.allStatus.length; i++){
    $('#ns_StatusClass').val($PAGE.allStatus[i].id);
    //$('#ns_StatusClass').trigger("chosen:updated");
}
$('#ns_StatusClass').trigger("chosen:updated");

but this results with only the last option in the for loop getting selected.

Is it not possible to set multiple options in the multi select chosen dropdown?

like image 969
man_luck Avatar asked Feb 12 '23 16:02

man_luck


2 Answers

To select multiple options use this code:

for(var i=0; i< $PAGE.allStatus.length; i++){
    $('#ns_StatusClass option[value='+$PAGE.allStatus[i].id+']').attr("selected", "selected");
}

use double quote if the value has one or more spaces:

for(var i=0; i< $PAGE.allStatus.length; i++){
    $('#ns_StatusClass option[value="'+$PAGE.allStatus[i].id+'"]').attr("selected", "selected");
}
like image 64
Ragnar Avatar answered Feb 14 '23 06:02

Ragnar


for the shorthand, you can use it like that

$('#ns_StatusClass').val([2,4]); // indexes of select values
$('#ns_StatusClass').trigger("chosen:updated");

like image 33
DeadMan Avatar answered Feb 14 '23 06:02

DeadMan