简体   繁体   English

从另一个多选2框中删除所选项目时,从多个select2框中删除所选项目

[英]Remove a selected item from multiple select2 box on removal of selected item from another multiple select 2 box

I have two multiple select2 boxes, Box1 options are populated dynamically,when i select any option from this select box, it should get added to the new Box2. 我有两个多个select2框,Box1选项是动态填充的,当我从这个选择框中选择任何选项时,它应该被添加到新的Box2中。 This scenario is working as required. 此方案根据需要运行。 Problem i am facing is. 我面临的问题是。 When i remove any selected item from the Box1, i am able to remove it from Box2. 当我从Box1中删除任何选定的项目时,我可以从Box2中删除它。 But if that item is selected in Box2 it still remains. 但如果在Box2中选择了该项目,它仍然存在。

Ex: A,B,C are selected values in Box 1, Box2 gets populated with A,B,C. 例如:A,B,C是框1中的选定值,Box2填充了A,B,C。 If i select B,c in Box 2 and if i remove B from Box1. 如果我在Box 2中选择B,c,如果我从Box1中删除B. My Box2 items will now be AC. 我的Box2项目现在将是AC。 But B,C will still remain selected in Box2. 但是B,C仍将在Box2中保持选中状态。

Can anyone help me in solving this tricky problem. 任何人都可以帮助我解决这个棘手的问题。

$("#Box1").on("change", function() {

    var box1List = $('#Box1').val();

    $('#Box2').empty();

    for (var key in box1List) {
        var valueField = box1List[key];
        var textField = $("#Box1 > option[value='"+valueField+"']").text();
        $("#Box2").append($('<option>', {value: valueField, text: textField}));
    }
});



$("#Box1").on("select2-removed", function(e) {

    console.log("removed val=" + e.val + " choice=" + e.choice.text);

    $('#Box2 option[value="'+e.val+'"]').remove();

});

After you alter the child <option> elements of a Select2 <select> element, you should call .change() on it to get it to update its display. 更改Select2 <select>元素的子<option>元素后,应调用它.change()以使其更新其显示。

$('#Box2').change();

But in your case, you probably also want to restore the value of the Select2 after you remove and re-add the options. 但在您的情况下,您可能还希望在删除并重新添加选项后还原Select2的值。

$("#Box1").on("change", function() {
    var val = $('#Box2').select2('val');
    $('#Box2').empty();
    $.each($('#Box1').select2('data'), function(i, item) {
        $("#Box2").append($('<option>', {value: item.id, text: item.text}));
    });
    $('#Box2').select2('val', val);
});

When you use .select2('val', val) to set the value, you do not need to call .change() . 使用.select2('val', val)设置值时,不需要调用.change()

jsfiddle 的jsfiddle

I have referenced from the post of Pierre de LESPINAY Glideh. 我引用了Pierre de LESPINAY Glideh的帖子。 And I tried to apply to my project. 我试图申请我的项目。

new_data = $.grep($('#my_input').select2('data'), function (value) {
    return value['id'] != id_to_remove;
});
$('#my_input').select2('data', new_data);

It worked fine. 它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM