JQuery-select2 - Get values ​​in the order in which they were selected

I am developing a form with several multiselects. For this, I use the Select2 library.

 $(".chosen-select").select2({
            allow_single_deselect: true,
            width: "150px"
        });
......
<select id="ship2" class="chosen-select" data-placeholder="Select vessel">
<option></option>
<option value="value1">title1</option>
<option value="value2">title2</option>
</select>

The problem is that when I try to get the selected values, they are returned in the order in which they are indicated in the element <select>, and not in the order in which they were selected:

var selectedDayPorts = $('#ship2');
var dayPorts = selectedDayPorts.select2("val");

Is there a way to get them in the correct order?

+3
source share
3 answers

I did not find a way to make select2 to store the values ​​in the correct order, so I finished creating hidden input fields for each select2 field and updated it accordingly when adding / removing new values

0
source

You can use:

var dayPorts = selectedDayPorts.select2("data");

:

alert(dayPorts[0]['id']);

alert(dayPorts[0]['text']);
0

Sometimes it can be help. After trying a few methods, I came up with a workaround using the code that I get with this link to the user shashilo. https://github.com/select2/select2/issues/3106

But I had to make a few arrangements, as this did not help me 100%. Here is my code.

$(".select2").on("select2:select", function (evt) {
          var element = evt.params.data.element;
          var $element = $(element);

          if ($(this).find(":selected").length > 1) {
            var $second = $(this).find(":selected").eq(-1);
            $second.after($element);
          } else {
            $element.detach();
            $(this).prepend($element);
          }

          $(this).trigger("change");
        });
Run codeHide result

In the link he mentioned

var $second = $(this).find(":selected").eq(-2);
Run codeHide result

But what worked for me was

var $second = $(this).find(":selected").eq(-1);
Run codeHide result

And it worked even when deselecting items in my case.

0
source

All Articles