问题
I'm developing a form with a number of multiselects. I use Select2 library for that.
$(".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 selected values they are returned in the order they are specified in <select>
element, not the order they have been selected:
var selectedDayPorts = $('#ship2');
var dayPorts = selectedDayPorts.select2("val");
Is there a way to get them in correct order?
回答1:
Sometimes this may be a help. After trying several methods I have came up with a workaround using the code i get with this link on user shashilo. https://github.com/select2/select2/issues/3106
But I had to do few arrangements as it didn't worked 100% on my case. 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");
});
In the link he mentioned
var $second = $(this).find(":selected").eq(-2);
But what worked for me was
var $second = $(this).find(":selected").eq(-1);
And this worked well even with deselecting items too in my case.
回答2:
You can use:
var dayPorts = selectedDayPorts.select2("data");
And get values:
alert(dayPorts[0]['id']);
alert(dayPorts[0]['text']);
回答3:
I didn't find a way how to make select2 to store values in the correct order, so I ended up creating hidden input fields for each select2-field and update it accordingly as I add/remove new values
来源:https://stackoverflow.com/questions/21680081/jquery-select2-get-values-in-the-order-they-were-selected