Matthieu Napoli
Matthieu Napoli

Reputation: 49693

How to automatically reorder a Sortable jQuery UI list?

I have 2 jQuery UI sortable lists (http://jqueryui.com/demos/sortable/#connect-lists).

I drag items from list A (catalog) to list B (basket).

What I want is for the lists (A and B) to reorder themselves automatically when an item is added (sorted by price). So when an item is dropped into the basket, it will go to its position (top/middle/bottom) according to its price.

Upvotes: 1

Views: 4101

Answers (2)

jValdron
jValdron

Reputation: 3418

You should use the "receive" event form sortable in conjunction with the sort method.

$('.list_a, .list_b').sortable({
    receive: function(){

        $('.list_a').html($('.list_a').get().sort(sortByPrice));
        $('.list_b').html($('.list_b').get().sort(sortByPrice));

        // As we replaced the content of the list, you probably need to 
        // make it sortable again... kind of a big hack

    }
});

function sortByPrice(a, b){

    // The parseFloat will not work if you have text before the price
    // in the price container.

    var price_a = parseFloat($('.price_selector', a).text());
    var price_b = parseFloat($('.price_selector', b).text());

    if(price_a < price_b) return -1;
    if(price_a > price_b) return 1;

    return 0;

}

Upvotes: 1

arb
arb

Reputation: 7863

I don't think there is a built in sorting mechanism like you've describted for the jQuery UI sortable lists. However, you could use this jQuery plugin to manually sort the items. It's very light weight and lets you control how things are sorted by defining a sorting function.

You could attach the sorting routine to the receive event of your "basket list." In that event, you would sort the items in the basket list by looking at their price and comparing them numerically. Pay attention to the second parameter of sortElements. It allows you to tell the sorter what element you actually want to move. Though in this case, just moving the li item might be fine.

Upvotes: 0

Related Questions