问题
I am using multiple options for Select2 and the data is loaded from a JSON source.
As I'm not sure how to explain it exactly I'll provide an example:
List Options:
- A
- B
- C
If I choose C, then
$("#select2").change(function(){
alert($(this).val());
});
Results: [C]
However, If I then choose A I would get [A, C]
If I then choose B I get [A, B, C]
I would preferably want it to append so I would get [C, A, B]. However being able to find the last selected option would be alright. I have tried :last and other answers but nothing seems to work.
Thanks in advance.
My script for Select2:
$.getJSON('profile/Skills.json', function (json) {
var mainList = [];
for (var TradeName in json) {
if (json.hasOwnProperty(TradeName)) {
var item = json[TradeName];
mainList.push(item.TradeName);
}
}
$(".chyeaSelect").select2({
data:mainList
});
});
回答1:
I believe you're looking for something like this:
$.getJSON('https://demo8858242.mockable.io/list', function (json) {
var mainList = [];
for (var TradeName in json) {
if (json.hasOwnProperty(TradeName)) {
var item = json[TradeName];
mainList.push(item.TradeName);
}
}
$(".select1").select2({
data:mainList
});
});
var array = [];
$(".select1").change(function(){
//alert($(this).val());
array.unshift($(this).val());
alert(array);
});
// Alternate
//$(".select1").change(function(){
// alert($(this).val());
// //$('.selected').prepend($(this).val());
//});
Codepen
回答2:
I guess it's too late for your problem, but maybe this can help someone else. I use :
$('#select2').on('select2:select', function(e: any) {
console.log(e.params.data.id);
});
Same with "select2:unselect".
来源:https://stackoverflow.com/questions/37094429/get-last-selected-value-of-select2