如何获得select2的值:取消选择

Vip*_*ngh 13 javascript jquery 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');
Run Code Online (Sandbox Code Playgroud)

在上面的代码警报显示'null'

我需要使用,select2:unselect因为'change'事件会感觉到:select并且:unselect两者兼而有之.

Chu*_*hun 13

实际上,数据值在事件Object内.如果您正在处理select2多个值,那将非常有用.

function(e){
    console.log(e.params.data)
}
Run Code Online (Sandbox Code Playgroud)

  • 具体来说,“ e.params.data.id”是选定/未选定项目的“值”,而“ e.params.data.text”则是“ innerText”标签。 (2认同)

gfr*_*ius 8

这是一个较老的问题,但也许这个答案会对某人有所帮助.我正在使用带有多个值/标签的Select2 v4.0.3,并且只需删除特定ID的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.
    */
Run Code Online (Sandbox Code Playgroud)


Vip*_*ngh 6

最后,我得到了解决方案,那就是:unselected选项的值仅在未选择之前可用。没有select2:unselect,而在select2:unselecting 现在的代码将是:

$('#mySelect').on("select2:unselecting", function(e){
         var unselected_value = $('#mySelect').val();
         alert(unselected_value);
    }).trigger('change');
Run Code Online (Sandbox Code Playgroud)

  • 这将适用于单个选择。要从多个选择中删除项目,请参阅上面的gfrobenius的答案。 (2认同)

小智 6

未选择的元素通过 e.params.data。我们可以使用“id”访问它的值,如果您需要文本,您可以使用“data.text”。

 $("select").on("select2:unselect", function (e) {
             var value=   e.params.data.id;
             alert(value);
    });
Run Code Online (Sandbox Code Playgroud)