Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move and remove Listbox item to another listbox using jQuery in same places

I have 2 multi select boxes like as in this link. http://jsfiddle.net/bdMAF/38/

$(function(){
    $("#button1").click(function(){
        $("#list1 > option:selected").each(function(){
            $(this).remove().appendTo("#list2");
        });
    });

    $("#button2").click(function(){
        $("#list2 > option:selected").each(function(){
            $(this).remove().appendTo("#list1");
        });
    });
});

But When i add from one first select box to second select box it is working fine for me.But again when i add from second select box to first select box they are appending to last of first select box.But what i want is i need to add they must be added in the place where they deleted.

Thanks in advance...

like image 228
PSR Avatar asked Jun 14 '13 12:06

PSR


2 Answers

Maybe you can simply set and remove the attribute "disabled" but it will leave a blank space in the options. Note that with this method you will need to clone the option the first time.

The other solution whould be to add the content as usual but applying a sort() function before

function byValue(a, b) {
    return a.value > b.value ? 1 : -1;
};

function rearrangeList(list) {
    $(list).find("option").sort(byValue).appendTo(list);
}

$(function () {
    $("#button1").click(function () {
        $("#list1 > option:selected").each(function () {
            $(this).remove().appendTo("#list2");
            rearrangeList("#list2");
        });
    });

    $("#button2").click(function () {
        $("#list2 > option:selected").each(function () {
            $(this).remove().appendTo("#list1");
            rearrangeList("#list1");
        });
    });
});

You can try at this fiddle

like image 103
Edorka Avatar answered Sep 17 '22 11:09

Edorka


You need to keep track of some sort of index, I think in your case you can use the value of each option. (but you could use a dedicated data-* attribute if you need to)

With that value you can then search the current list and see where it should fit in. Loop the options and check for a value greater than the one you are moving. If you find one then insert it before that, if you don't fine one then insert at the end.

This should do it:

$("#button2").click(function(){
    $("#list2 > option:selected").each(function(){
        var item = $(this).remove();
        var match = null;
        $("#list1").find("option").each(function(){
            if($(this).attr("value") > item.attr("value")){
                match = $(this);
                return false;
            }
        });
        if(match)
            item.insertBefore(match);
        else
           $("#list1").append(item);
    });
});

You can apply the same for the reverse too.

Here is a working example

like image 25
musefan Avatar answered Sep 17 '22 11:09

musefan