13

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?

2 Answers2

35

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"));
Sean Kenny
  • 1,626
  • 13
  • 14
  • Sorry for the misunderstanding. I don't want to add an option, I want to select an option. Also, I doubt that this would work without re-initializing the select2 plugin. –  Jun 04 '13 at 11:15
  • 8
    Why the down vote? You did state 'I need to add values to the selected list.' :-) And it does work without reinitialising the plugin. Try it. – Sean Kenny Jun 04 '13 at 11:19
  • _Selected_, not _select_. Also, if you would've looked at the code, you'd see that I was changing the value (thus the selected onces) and not the options of the select. It might work, it doesn't do what I asked, so it isn't an answer to my question. I'll rephrase it to make it more clear. –  Jun 04 '13 at 11:20
  • Thanks, that's what I was looking. But is there a command for `select2` to do this, so that I don't need three lines? –  Jun 04 '13 at 11:36
  • Great - that's better! There doesn't seem to be anything on select2 to do this - (https://github.com/ivaynberg/select2/blob/master/select2.js#L3011). You could always extend the plugin yourself if you really wanted to. – Sean Kenny Jun 04 '13 at 11:40
  • I tried this and it wont add selected value instead changed all value to the first element of the array. :( – Yakob Ubaidi Mar 16 '17 at 05:29
  • @SeanKenny you are the man bro don't ever let anybody tell you otherwise. – a2f0 Feb 27 '18 at 23:05
1

This is how i do it:

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

HTH

Shai Efrati
  • 516
  • 1
  • 7
  • 27