使用 jQuery 仅将唯一项目从一个多 Select 列表移动到另一个

Move only unique Items from One Multi Select List To Another using jQuery

这是我的 select 盒子...

<select id="selectOne" multiple style="height: 150px">
 <option>March 2018</option>
 <option>May 2018</option>
 <option>January 2019</option>
 <option>August 2020</option>
</select>

<button type='button' id="btnRight"> >> </button>
<button type='button' id="btnLeft"> << </button>

<select id="selectTwo" multiple style="height: 150px">
 <option>Anaconda</option>
 <option>Daniel</option>
 <option>Jack</option>
 <option>March 2018</option>
</select>

这是我的 jquery

$(function() {
 function moveItems(origin, dest) {
  $(origin).find(':selected').appendTo(dest);
 }

function moveAllItems(origin, dest) {
 $(origin).children().appendTo(dest);
}

$('#btnLeft').click(function() {
 moveItems('#selectTwo', '#selectOne');
 });

 $('#btnRight').on('click', function() {
   moveItems('#selectOne', '#selectTwo');
 });

});

我可以移动 select 选项,但如果右侧 select 框中存在任何选项,我只想移动唯一选项,然后保留移动数据并删除现有数据。

这是 jsfiddle link。

https://jsfiddle.net/uthpal/g60sertc/

我将所选项目存储在某处。为了检查目的地中的现有项目,我逐一检查每个选择的项目。我将在代码中进行解释以使其更容易。

function moveItems(origin, dest) {
    var o = $(origin).find(':selected');
    for (var i = 0; i < o.length; i++) {
        for (var j = 0; j < $(dest).children().length; j++) {
            if ($(dest).children()[j].text == o[i].text){
                break; // stop looping once the selected item is found in destination.
            }
        }
        var temp = $(dest).children().length; // keep the original destination size
        $(dest)[0].appendChild(o[i]);
        if (j != temp) { // remove the duplicate item in destination 
            $(dest)[0].removeChild($(dest)[0].lastChild);
        }
    }
}