1
$(document).ready(function() {

    $('#new-to-do-item').keyup(function(e) {
        if (e.which === 13) {
           var text = $(this).val();
           var listItem = "<li><input type='checkbox'>" + text + "</li>"
           $(listItem).appendTo('.list');
        }
     });

    //sort
    $(document).on('click', '#coolthings',function(){
        $(".list li").sort(asc_sort).appendTo('.list');
        //$("#debug").text("Output:");
        // accending sort
       function asc_sort(a, b){
           return ($(b).text()) < ($(a).text()) ? 1 : -1;    
       }
}); 

I have a list that initially consist of 4 items, and #coolthings is a element that when i click, will sort those items in alphabetical order, however, the keyup function appends new items to the list, and the #coolthings button will not sort the WHOLE list along with the newly added items, it will sort the initial list alphabetically, followed by new items added alphabetically, making the entire list consisted of two alphabetical lists. I wonder how can i make it so the sort button will sort the ENTIRE list in alphabetical order after i added the new items with keyup function.

cr0ss
  • 877
  • 5
  • 20
frankcrest
  • 107
  • 1
  • 5
  • 12
  • You don't have a closing of `#coolthings` click event, is this a typo? – Jai May 27 '14 at 19:18
  • looks like you need to sort the list intially first and then **insert** the new item at the right index instead of adding/appending the new item. That's the most efficient dynamic sorting (like how binary tree stores the data for quick searching). – King King May 27 '14 at 19:21
  • @KingKing but that would defeat the purpose of having the "sort" button then, since you are suggesting to append the new li items in alphabetical order already – frankcrest May 27 '14 at 19:24

4 Answers4

2

You cannot sort HTML elements, but need to detach them first (and re-attach them after they were sorted).

This will work (see here):

$(function(){
     $('#new-to-do-item').keyup(function(e) {
         console.log(e.which == 13);
         if (e.which == 13) {
           var text = $(this).val();
           var listItem = "<li><input type='checkbox'>" + text + "</li>";
           $(listItem).appendTo('.list');
           $(this).val('');
        }
     });

    $(document).on('click', '#coolthings',function(){
        $(".list li").detach().sort(asc_sort).appendTo('.list');
       function asc_sort(a, b){
           return ($(b).text()) < ($(a).text()) ? 1 : -1;    
       }
    });
});
muffel
  • 7,004
  • 8
  • 57
  • 98
  • hey man, thanks for the reply, however, it does not work with my html, is my html wrong or something, here is my html http://jsfiddle.net/48T4U/3/ – frankcrest May 27 '14 at 19:40
  • @frankcrest what is not working? the only part which could be implemented is [case-insensitivity](http://jsfiddle.net/48T4U/4/), but adding new items and sorting them works like a charm for me – muffel May 27 '14 at 19:42
  • in fact without using `detach()`, it also works OK http://jsfiddle.net/viphalongpro/48T4U/5/ – King King May 27 '14 at 19:43
2

With Char Order Maintained uses tinysort plugin:

http://jsfiddle.net/EJ9y7/3/

Refer here

Also the sorting function may need a better way from sorting hints

$(document).ready(function () {
    $('#new-to-do-item').keyup(function (e) {
        if (e.which === 13) {
            var text = $(this).val();
            var listItem = "<li><input type='checkbox'>" + text + "</li>";
            $(listItem).appendTo('.list');
        }
    });
});

//sort
$(document).on('click', '#coolthings', function () {
    var sorted = $(".list li").sort(asc_sort);
    $(".list").append(sorted);
    function asc_sort(a, b) {
        return ($(b).text().toUpperCase()) < ($(a).text().toUpperCase()) ? 1 : -1;

    }
});
Community
  • 1
  • 1
Abs
  • 3,902
  • 1
  • 31
  • 30
  • 1
    thank you so much, worked perfectly, from what i understand, the empty function empties the entire list, and then the append function adds the entire list sorted into the list again, and then the new list is displayed? – frankcrest May 27 '14 at 19:45
  • @frankcrest the magic is not what `.empty()` does, the magic is the `.toUpperCase()`, if you want to sort it **case-insensitively**, you should convert all the text into lower-case or upper-case, otherwise the sorting will be unexpected. Your original example has all the 4 items starting with capitalized letters, while testing, we just typed in some lower-case letters and hence unexpected result. – King King May 27 '14 at 20:17
  • @KingKing oh wow, i see why it was the way it was then, so is the empty() necessary and is it what i thought it did? – frankcrest May 28 '14 at 02:00
  • @frankcrest no, `empty()` is not necessary. – King King May 28 '14 at 03:13
  • http://jsfiddle.net/EJ9y7/3/ Most comphrensive way is Using Tsort plugin to ensure char order as well. Empty is not required as mentioned. – Abs May 28 '14 at 06:00
0

The problem is you sort just javascript list. You do not sort html list. It's because $(".list li") return javascript representation of <li> nodes. If you want to display it, you must rearrange html tree. The easiest way I think is to erase content of list node and reinsert <li> nodes.

Piotr Karasiński
  • 339
  • 1
  • 2
  • 10
0

Although muffle's solution works, detach() is NOT the reason yours did not work.

I assume your html looks something like this

<ul class="list">
    <li> <input type='checkbox'>hi</li>
    <li> <input type='checkbox'>bi</li>
    <li> <input type='checkbox'>zi</li>
    <li> <input type='checkbox'>ai</li>
</ul>

when it should actually look like this

<ul class="list">
    <li><input type='checkbox'>hi</li>
    <li><input type='checkbox'>bi</li>
    <li><input type='checkbox'>zi</li>
    <li><input type='checkbox'>ai</li>
</ul>

that space would cause your initial hardcoded elements to always be alphabetized before 'a'. Fixing your initial html or stripping whitespace would be the solution.

After viewing your HTML, your issue is capitalization is prioritized before lowercase. You're probably testing additional input with lower case

Nick Avi
  • 1,231
  • 2
  • 7
  • 6
  • my html does not look like that, I have posted my html and muffel's answer in a jfiddle in the comments, it did not work – frankcrest May 27 '14 at 19:50
  • See here http://stackoverflow.com/questions/8996963/how-to-perform-case-insensitive-sorting-in-javascript – Nick Avi May 27 '14 at 19:52