如何在 Select2 中获取未选择选项的值?使用 select2:unselect
$('#mySelect').on("select2:unselect", function(e){
var unselected_value = $('#mySelect').val(); // using this shows 'null'
// or using below expression also shows 'null'
var unselected_value = $('#mySelect :selected').val();
alert(unselected_value);
}).trigger('change');
在上面的代码中警告显示'null'
我需要使用 select2:unselect
因为 'change' 事件会感知 :select
和 :unselect
两者。
最佳答案
这是一个较旧的问题,但也许这个答案会对某人有所帮助。我正在使用具有多个值/标签的 Select2 v4.0.3,只需要删除特定值/标签的 ID。我真的不想使用其他答案中提到的 unselecting
事件。在 unselect
事件中没有 args
对象,因此您可以像这样获取您要删除的对象的 ID...
jQuery('.mySelect2').on("select2:unselecting", function(e){
return true; // I don't use this unselecting event but here is how you could use it to get the ID of the one you are trying to remove.
console.log(e);
console.log(e.params);
console.log(e.params.args.data);
console.log(e.params.args.data.id);
//console.log(e.params.args.data.tag); data.tag is specific to my code.
});
jQuery('.mySelect2').on('select2:unselect', function (e) {
console.log(e);
console.log(e.params);
console.log(e.params.data);
console.log(e.params.data.id);
//console.log(e.params.data.tag); data.tag is specific to my code.
/*
Now you can do an ajax call or whatever you want for the specific
value/tag that you are trying to remove which is: e.params.data.id.
*/
关于javascript - 如何获取select2 :unselect的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463714/