Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alphabetically sort a JQuery UI sortable?

I was wondering if it is possible to have a JQuery UI sortable default to be alphabetically sorted. If so, is it also possible to keep it alphabetically sorted in real time if I add items to the sortable? Below is my code:

// Adds item to sortable list
$(".addButton").click(function(e) {
    e.preventDefault();
    // set var item to be the string inputted by the user
    var item = $("input[name='brewItem']").val();
    // parses input string, splitting at commas into liArray containing substrings as elements
    var liArray = item.split(", ");
    // for loop to add each brew to the sortable list (length-1 because last element in array is empty string)
    for (var i = 0; i < liArray.length-1; i++) {
        // sets var $li to the string in the ith index of liArray
        var $li = $("<li class='ui-state-default'/>").text(liArray[i]);



        // adds var $li to gui
        $("#sortable").append($li);
    };
    // refreshes the page so var $li shows up
    $("#sortable").sortable("refresh");
});

I'm not quite sure where or how to implement this. Any help is appreciated, thanks!

like image 697
sbru Avatar asked Apr 15 '13 02:04

sbru


1 Answers

You need to tweak it to make it sort as you need.

Try this:- Fiddle

Use custom sort method

 function sort() {
    var sortableList = $('#sortable');
    var listitems = $('li', sortableList);

    listitems.sort(function (a, b) {

        return ($(a).text().toUpperCase() > $(b).text().toUpperCase())  ? 1 : -1;
    });
    sortableList.append(listitems);

}

Call it in your sortable's create event Create and in Button Click

$("#sortable").sortable({
    create: function (event, ui) {
        sort();
    }
});

Or Extend jquery ui sortable widget to include your custom sorting logic.

like image 145
PSL Avatar answered Sep 18 '22 21:09

PSL