Search code examples
jquery-select2html-selectjquery-select2-4

Get selected option in Select2 event, when multiple options can be selected


How can I get hold on the <option> that was just selected when listening to the select2:select event? Note that this is simple when using a single-select, as when only one option is selected, that must be the one that was just selected. I would like to also be able to find the option that was just selected when using a multiple-select (<select multiple>).

In the select2:unselect event, the unselected <option> is available through e.params.data.element, but it is not so in the select2:select event. I do not see a reason why the <option> should not be available, since it is created at this time. For the select2:selecting event, however, the <option> is not yet created, and obviously cannot be available when the event is fired.


Solution

  • I've used the following to get the current selected in Select2 (it's for version 4 and up):

    // single value
    var test = $('#test');
    test.on("select2:select", function(event) {
      var value = $(event.currentTarget).find("option:selected").val();
      console.log(value);
    });
    

    UPDATE: Multi Selected Values (with and without last selected)

    // multi values, with last selected
    var old_values = [];
    var test = $("#test");
    test.on("select2:select", function(event) {
      var values = [];
      // copy all option values from selected
      $(event.currentTarget).find("option:selected").each(function(i, selected){ 
        values[i] = $(selected).text();
      });
      // doing a diff of old_values gives the new values selected
      var last = $(values).not(old_values).get();
      // update old_values for future use
      old_values = values;
      // output values (all current values selected)
      console.log("selected values: ", values);
      // output last added value
      console.log("last added: ", last);
    });