【问题标题】:Move only unique Items from One Multi Select List To Another using jQuery使用 jQuery 仅将唯一项目从一个多选列表移动到另一个
【发布时间】:2018-07-10 01:14:30
【问题描述】:

这是我的选择框...

<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');
 });

});

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

这里是 jsfiddle 链接。

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

【问题讨论】:

  • 例如,如果我将March 2018移动到右侧,它只会在右侧显示一个,而左侧不包含March 2018。这就是你想要的吗?
  • 是的,我想要大卫兄弟。
  • 那么,我想我的回答可以解决你的问题。
  • 感谢大卫兄弟,它工作正常...... :)
  • 没问题。也许您想将我的答案标记为正确,以便与您有类似问题的其他人可以得到答案。

标签: jquery duplicates move


【解决方案1】:

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

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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多