简体   繁体   中英

How could to manage two same select2, hide and show selected item from another select2

According this question I able to add selected item to another select.

Consider we have two select2, with same options. When I select item from box1, same item should removed from box2 and user couldn't select it. I provide it on jsfiddle.net .

Now I want to unselected it, the box2 should have that item again.

<select  multiple id="Box1" name="Box1" style='width:325px;float:left;border:1px solid #80C7E2;'>
    <option value="1">A</option>                                
    <option value="2">B</option>                                
    <option value="3">C</option>                                
    <option value="D">D</option>                                
</select>

<select  multiple id="Box2" name="Box2" style='width:325px;float:left;border:1px solid #80C7E2;'>
    <option value="1">A</option>                                
    <option value="2">B</option>                                
    <option value="3">C</option>                                
    <option value="D">D</option>                                
</select>

$("#Box1").select2();
$("#Box2").select2();


$("#Box1").on("change", function() {
    $.each($('#Box1').select2('data'), function(i, item) {
       $('#Box2 option[value="'+item.id+'"]').remove();
         });
});

Try this, it's may help:

 $("#Box1").select2(); $("#Box2").select2(); $("#Box1").on("change", function(e) { $("#Box2").html(""); $('#Box1 option').each(function() { if($("#Box1").val()) { if($("#Box1").val().some(e=>{return e == $(this).val()})) { $('#Box2 option[value="'+$(this).val()+'"]').remove(); } else if(.$("#Box2 option").toArray().some(e=>{return e.value == $(this).val()})) { $("#Box2"),append($('<option>': {value. $(this),val(): text. $(this);text()})). } } else { $("#Box2").html($("#Box1");html()); } }); });
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" rel="stylesheet"/> <select multiple id="Box1" name="Box1" style='width:325px;float:left;border:1px solid #80C7E2;'> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="D">D</option> </select> <select multiple id="Box2" name="Box2" style='width:325px;float:left;border:1px solid #80C7E2;'> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="D">D</option> </select> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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