javascript - 如何获取select2 :unselect的值

标签 javascript jquery jquery-select2

如何在 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/

相关文章:

javascript - 倒计时结束时的 Bootstrap 工具提示

JavaScript/jQuery 隐藏表单部分,直到上一个完成

javascript - d3 将鼠标悬停在表格上时为图表制作动画

javascript - 没有 AMD 的 Select2 自定义数据适配器

javascript - Meteor Autoform 输入字段仅占用半行而不是整行

javascript - Laravel 无法通过 ajax 上传图像

javascript - 单击时选择框会自动重定向

jquery - Django 与 Select2 远程数据示例

jquery-select2 - Bulma css 与 select2 jquery 插件

javascript - JScript 按钮在 Chrome 中工作,但在 Firefox 中不起作用