Keep selected items at the top of the list.

I am trying to create a checklist that will sort the marked items at the top of the list, and when the item is not checked, it will move below the marked items. In addition to the check / unchecked appearance, the elements must remain in the original order, regardless of the order in which they are checked.

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

Not this:
* three
* two
one
four
five

I saw examples of moving clicks of elements to a specific position in the list, but nothing takes into account the state of other elements in the list.

Ideally, I would also like to enliven 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> 
+4
source share
2 answers

Select the source list to save the order. When one of these checkboxes is clicked, click on it by first adding checked items and unverified items:

 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

+4
source

ok try the following:

html:

 <form> <ul> <li id="1"><label for="one"><input type="checkbox" id="one" />One</label></li> <li id="2"><label for="two"><input type="checkbox" id="two" />Two</label></li> <li id="5"><label for="five"><input type="checkbox" id="five" />Five</label></li> <li id="3"><label for="three"><input type="checkbox" id="three" />Three</label></li> <li id="4"><label for="four"><input type="checkbox" id="four" />Four</label></li> </ul> </form> 

JavaScript:

 function sortNum(a,b){ a = $(a); b = $(b); if( a.find("input").is(':checked') && !b.find("input").is(':checked') ) return -1; if( !a.find("input").is(':checked') && b.find("input").is(':checked') ) return 1; else return a.attr('id') > b.attr('id') ? 1 : -1; }; 

now to change them use:

 $("li").sort(sortNum).appendTo("ul"); 
+2
source

Source: https://habr.com/ru/post/1389516/


All Articles