使用JQuery将一个组合框中的选定项添加到另一个组合框中

时间:2011-09-27 14:14:52

标签: jquery appendto

我正在尝试找到将所选项目从一个组合框添加到另一个组合框的最佳方法。诀窍是我只想将项目添加到目标列表中但尚不存在。目前我使用的过程相当丑陋,并没有像我期望的那样工作。

$('#addSelectedButton').click(function() {
    var previousOption;
    $('#sourceList option:selected').appendTo('#destinationList');
    $('select[name=destinationList] option').each(function () {
        if (this.text == previousOption) $(this).remove();
        previousOption = this.text;
    });
});

我遇到的问题是 appendTo 方法更多的是移动而不是添加。然后就是删除重复项的问题,这在本例中有效,但我不禁想到有更好的方法。

非常感谢任何协助。

谢谢,

4 个答案:

答案 0 :(得分:5)

使用clone()grep()您可以轻松实现这一目标。首先 clone 从源中选择的选项,然后使用 grep ,您可以过滤掉目标列表中已有的项目。

$('#addSelectedButton').click(function() {
    // select this once into a variable to minimize re-selecting
    var $destinationList = $('#destinationList');

    // clone all selected items
    var $items = $.grep($('#sourceList option:selected').clone(), function(v){
        // if the item does not exist return true which includes it in the new array
        return $destinationList.find("option[value='" + $(v).val() + "']").length == 0;

    });

    // append the collection to the destination list
    $destinationList.append($items);
});

工作示例: http://jsfiddle.net/hunter/4GK9A/


<强> clone()

  

创建匹配元素集的深层副本。

<强> grep()

  

查找满足过滤函数的数组元素。原始数组不受影响。

答案 1 :(得分:1)

我认为你想要的是将“clone”与append:

结合使用

http://api.jquery.com/clone/

答案 2 :(得分:1)

您可以像这样使用clone():

$('#addSelectedButton').click(function() {
    var previousOption;
    var clone =  $('#sourceList option:selected').clone();
    clone.appendTo('#destinationList');
    $('select[name=destinationList] option').each(function () {
        if (this.text == previousOption) $(this).remove();
        previousOption = this.text;
    });
});

答案 3 :(得分:1)

您只需在目的地列表中搜索包含的值即可。 http://jsfiddle.net/EHqem/

$('#addSelectedButton').click(function() {
    $('#sourceList option:selected').each(function(i, el) {
        if ($('#destinationList option[value='+$(el).val()+']').length === 0) {
           $('#destinationList').append($(el).clone());
        }
    });
});