开发者

Using JQuery to add selected items from one combobox to another

I'm trying to find the best way to add selected items from one combobox to another. The trick is I only want to add items to the destination list that don't already exist. Currently the process I use is rather ugly and does not work as I would expect.

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

The problem I'm having is that the appendTo method acts as more of a move rather than an add. Then there's the problem of removing the duplicates, which works in this this example, but I can't help but think there's a better way.

Any assistance would be greatly开发者_Python百科 appreciated.

Thanks,


using clone() and grep() you can achieve this easily. First clone the options that are selected from the source and then using grep you can filter out the items that are already in the destination list.

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

Working Example: http://jsfiddle.net/hunter/4GK9A/


clone()

Create a deep copy of the set of matched elements.

grep()

Finds the elements of an array which satisfy a filter function. The original array is not affected.


I think what you want is to use "clone" in conjunction with append:

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


You could use clone() like this:

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


You can just search the destination list for the containing value. 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());
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜