Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create a checklist that will sort checked items to the top of the list, and when an item is unchecked, it will move below the checked items. Beyond the checked/unchecked sort, items should stay in their original order, regardless of what order they are checked in.

In other words, a five item list should always look like this:
* two
* three
one
four
five

not this:
*three
*two
one
four
five

I've seen examples of how to move clicked items to a specific position in the list, but nothing that takes into account the state of other items in the list.

Ideally I'd also like to animate the transition. Also, is there a way to remember the checked state across multiple pages?

This is the HTML I'm starting with:

<form>
<ul>
<li><label for="one"><input type="checkbox" id="one" />One</label></li>
<li><label for="two"><input type="checkbox" id="two" />Two</label></li>
<li><label for="three"><input type="checkbox" id="three" />Three</label></li>
<li><label for="four"><input type="checkbox" id="four" />Four</label></li>
<li><label for="five"><input type="checkbox" id="five" />Five</label></li>
</ul>
</form>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
388 views
Welcome To Ask or Share your Answers For Others

1 Answer

Select the original list to save the order. When one of the checkboxes is clicked, iterate over it, appending the checked items first and the unchecked items second:

var list = $("ul"),
    origOrder = list.children();

list.on("click", ":checkbox", function() {
    var i, checked = document.createDocumentFragment(),
        unchecked = document.createDocumentFragment();
    for (i = 0; i < origOrder.length; i++) {
        if (origOrder[i].getElementsByTagName("input")[0].checked) {
            checked.appendChild(origOrder[i]);
        } else {
            unchecked.appendChild(origOrder[i]);
        }
    }
    list.append(checked).append(unchecked);
});

Demo: http://jsfiddle.net/scSYV/2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...