2011-09-27 61 views
2

我試圖找到從一個組合框添加選定項目到另一個組合框的最佳方法。訣竅是我只想將項目添加到不存在的目標列表中。目前我使用的過程相當醜陋,並不像我預期的那樣工作。使用JQuery將選定的項目從一個組合框添加到另一個組合框

$('#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方法充當多個移動,而不是附加的。然後有刪除重複的問題,這在這個例子中起作用,但我不禁想到有更好的方法。

任何援助將不勝感激。

感謝,

+0

您還可以添加html代碼段嗎? – Jayendra

回答

5

使用clone()grep(),你可以很容易地做到這一點。第一個克隆從源中選擇的選項,然後使用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

不錯的使用grep!忘了那個。 – rooney

1

您可以使用克隆()是這樣的:

$('#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; 
    }); 
}); 
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()); 
     } 
    }); 
}); 
相關問題