1

I want to sort a list with items. The sorting should be based on the data-element of each item.

The strange thing is, it works if you try it locally on your pc (download my sortingtest.html), but it doesn't work online in jfiddle, neither and more importantly on mobile phones!

Do you have an idea whats wrong with my code or how I could do it better so that it works also on mobile phones?

The Code:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
    function sortEntries() {    
        var elems = $('#mylist').children('li').remove();
        elems.sort(function(a,b){ 
            return parseInt($(b).data('vote')) > parseInt($(a).data('vote'));
        });
        $('#mylist').append(elems);
    }
    </script>
</head>

<body>

    <ul id="mylist">
        <li data-vote="2">Vote: 2</li>
        <li data-vote="4">Vote: 4</li>
        <li data-vote="1">Vote: 1</li>
        <li data-vote="5">Vote: 5</li>
        <li data-vote="3">Vote: 3</li>
    </ul>

    <a href="#" onClick="sortEntries();">Sort me!</a>

</body>
</html>

JFiddle: http://jsfiddle.net/Q82Qu/

HTML-File Download: (Save file as) https://copy.com/c0Ogb8wLtRrg

Big thanks in advance, Stee

2 Answers 2

1
var elems = $('#mylist').children('li').remove();

what above code do is remove DOM from the Document so you can not use it as elems.sort(

<html>
<head>
    <script src="js/jquery.js"></script>
    <script>
    function sortEntries()
    {
        var elems = $('#mylist').children('li');
        elems.sort(function(a,b){ 
            return parseInt($(b).data('vote')) > parseInt($(a).data('vote'));
        });
        $('#mylist').append(elems);
    }
    </script>
</head>

<body>

    <ul id="mylist">
        <li data-vote="2">Vote: 2</li>
        <li data-vote="4">Vote: 4</li>
        <li data-vote="1">Vote: 1</li>
        <li data-vote="5">Vote: 5</li>
        <li data-vote="3">Vote: 3</li>
    </ul>

    <a href="#" onClick="sortEntries();">Sort me!</a>

</body>
</html>
Sign up to request clarification or add additional context in comments.

Comments

1

I've sorted it out on my own:

The key is to use this sorting code:

elems.sort(function(a,b){ 
    return $(b).attr('data-vote') - $(a).attr('data-vote');
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.