Remove a selected item from multiple select2 box on removal of selected item from another multiple select 2 box
Asked Answered
T

2

5

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. 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. But if that item is selected in Box2 it still remains.

Ex: A,B,C are selected values in Box 1, Box2 gets populated with A,B,C. If i select B,c in Box 2 and if i remove B from Box1. My Box2 items will now be AC. But B,C will still remain selected in 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();

});
Topgallant answered 18/7, 2014 at 8:9 Comment(4)
Look at this link, try using built in callback events. runnable.com/UmuP-67-dQlIAAFU/events-in-select2-for-jqueryMaribeth
Thanks Siva.G i have already referred this link. But it dint help in solving my problem.Topgallant
can you please make some demo in fiddle with what you have tried so farMaribeth
jsfiddle.net/Gikar23/QTDy7/3Topgallant
G
5

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.

$('#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.

$("#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().

jsfiddle

Guanidine answered 16/12, 2014 at 21:35 Comment(0)
A
2

I have referenced from the post of 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.

Anapest answered 16/12, 2014 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.