I am using multiple options for Select2 and the data is loaded from a JSON source.
我正在为Select2使用多个选项,并且数据是从JSON源加载的。
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
如果我选择C,那么
$("#select2").change(function(){
alert($(this).val());
});
Results: [C]
However, If I then choose A I would get [A, C]
但是,如果我然后选择A我会得到[A,C]
If I then choose B I get [A, B, C]
如果我然后选择B我得到[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.
我最好希望它附加所以我会得到[C,A,B]。但是,能够找到最后选择的选项将是正常的。我试过:最后和其他答案但似乎没有任何效果。
Thanks in advance.
提前致谢。
My script for Select2:
我的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
});
});
2 个解决方案
#1
0
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());
//});
#2
0
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".
与“select2:unselect”相同。
#1
0
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());
//});
#2
0
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".
与“select2:unselect”相同。