Skip to content Skip to sidebar Skip to footer

JQuery Move Item From One Select Box To Another While Retaining Listing Order

I have this code that is working but when the item is moved, it shows up at the bottom of the list. I'd prefer to keep the order alphabetical and have no idea where to start. <

Solution 1:

You can use the sort method to keep the order you want

EXAMPLE sort by your option values

 youroptions.sort(function(a,b){
       return a.value - b.value;
 });

You can shorten your code quite a bit if you have your relative select elements as siblings inside a parent div by using siblings

$(document).ready(function() {
    $('select').change(function() {
        var $this = $(this);
        $this.siblings('select').append($this.find('option:selected')); // append selected option to sibling
        $('select', $this.parent()).each(function(i,v){ // loop through relative selects
            var $options = $(v).find('option'); // get all options
            $options = $options.sort(function(a,b){ // sort by value of options
                return a.value - b.value;
            });
            $(this).html($options); // add new sorted options to select
        });
    });   
});​

http://jsfiddle.net/e6Y7J/


Post a Comment for "JQuery Move Item From One Select Box To Another While Retaining Listing Order"