首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获得select2 2的值:unselect

如何获得select2 2的值:unselect
EN

Stack Overflow用户
提问于 2015-12-25 14:32:57
回答 9查看 32.3K关注 0票数 18

如何在Select2中使用select2:unselect获得未选择选项的值

代码语言:javascript
运行
复制
$('#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

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2015-12-25 15:32:42

最后,我得到了解决方案,即:未选择选项的值只有在未选择之前才可用。现在不是在select2:unselect,而是在select2:unselecting,代码将是:

代码语言:javascript
运行
复制
$('#mySelect').on("select2:unselecting", function(e){
         var unselected_value = $('#mySelect').val();
         alert(unselected_value);
    }).trigger('change');
票数 9
EN

Stack Overflow用户

发布于 2017-01-13 19:12:13

这是一个较老的问题,但也许这个答案会对某人有所帮助。我使用的是带有多个值/标记的Select2 v4.0.3,只需要删除特定值的ID。我真的不想像其他答案中提到的那样使用unselecting事件。在unselect事件中没有args对象,所以您可以获得您试图删除的ID,如下所示.

代码语言:javascript
运行
复制
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.
    */
票数 16
EN

Stack Overflow用户

发布于 2016-03-24 15:52:08

实际上,数据值在事件对象中。如果您处理的是select2多个值,这将是有用的。

代码语言:javascript
运行
复制
function(e){
    console.log(e.params.data)
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34463714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档