man_luck
man_luck

Reputation: 1656

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?

Upvotes: 7

Views: 8850

Answers (2)

DeadMan
DeadMan

Reputation: 21

for the shorthand, you can use it like that

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

Upvotes: 1

Ragnar
Ragnar

Reputation: 4578

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");
}

Upvotes: 10

Related Questions