0

I have the following HTML

<ul class="aa-checkbox-list aa-tick_group_test-list">

   <li data-aa-position="1" data-aa-checked="1" data-aa-name="B"><label>
  <input class="custom-control-input" name="some_tick" type="checkbox">
</label></li>


   <li data-aa-position="2" data-aa-checked="1" data-aa-name="A"><label>
  <input class="custom-control-input" name="some_tick2" type="checkbox">
</label></li>


<li data-aa-position="3" data-aa-checked="0" data-aa-name="D"><label>
  <input class="custom-control-input" name="some_tick4" type="checkbox">
</label></li>


<li data-aa-position="4" data-aa-checked="0" data-aa-name="C"><label>
  <input class="custom-control-input" name="some_tick3" type="checkbox">
</label></li>

</ul>

And the following jQuery:

function tick_group_test__sort(){
    $(".aa-tick_group_test-list li").sort(sort_li).appendTo('.aa-tick_group_test-list');

    function sort_li(a, b) {
        var x = ($(a).data('aa-checked') < $(b).data('aa-checked')) ? -1 : ($(a).data('aa-checked') > $(b).data('aa-checked')) ? 0 : 1;
        return x;
    }
};

I am firstly trying to order the list based on "aa-checked" in Descending order, so elements that contain a checked input are at the top

Then for the checked ones (1), sort them alphabetically, for the unchecked ones (0), sort them by their "aa-position"

Been trying for hours and can't for the life of me figure it out

1 Answer 1

0

You are looking for this sort callback function:

function sort_li(a, b) {
    return $(b).data('aa-checked') - $(a).data('aa-checked')
        || ($(a).data('aa-checked') 
              ? $(a).data('aa-name').localeCompare($(b).data('aa-name'))
              : $(a).data('aa-position') - $(b).data('aa-position')
           );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly, thank you very much, I haven't stopped working on it since I made the post

Your Answer

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