user1544337
user1544337

Reputation:

Adding values to a multiple select with jQuery's select2

I'm using the select2 jQuery plugin on a <select> with multiple="multiple". I need to add values to the selected list (i.e. not to all the options, but to the selected options, without adding a new option).

I know I can set the selected options with this:

$("#the_select").select2("val", "the_option_value"); 

Or, for multiple selections:

$("#the_select").select2("val", ["an_option_value","another_option_value"]); 

However, is there a way I can add selected options to the list (i.e. make an option selected) without removing the others?

Upvotes: 13

Views: 41713

Answers (2)

Shai Efrati
Shai Efrati

Reputation: 524

This is how i do it:

      $("#the-select")
        .val($("#the-select")
          .val()
          .concat([array_of_existing_values]));
      $("#the-select")
        .trigger("change");

HTH

Upvotes: 1

Sean Kenny
Sean Kenny

Reputation: 1636

You should be able to use this:

$("#the_select").append($('<option>', {value:"NEWVAL", text: "New Option Text"}));

It will append the new option item to the end of the list.

HTH

Edit

Take 2 :) - I tried this in chrome dev tools over on the select2 page. It works (I added "WA" and Washington appeared.

var selectedItems = $("#the_select").select2("val");
selectedItems.push("NEWITEMVAL");   // I used "WA" here to test.
$("#the_select").select2("val", selectedItems);

Or as a one liner:

$("#the_select").select2("val", $("#the_select").select2("val").concat("NEWITEMVAL"));

Upvotes: 35

Related Questions