Skip to content Skip to sidebar Skip to footer

How To Sort Checkboxes By Class, Value, And Checked

I have a div, #subfilterNamesContainer, that contains a list of checkboxes. I am trying to write a function that will sort the checkboxes in to 3 sections. Checkboxes with class=

Solution 1:

Firstly you would need to amend your HTML slightly so that when the checkboxes are re-arranged the text node next to them is moved as well. To do this, you can surround both nodes with a label element, like this:

<div id="subfilterNamesContainer">
    <label>
        <input type="checkbox" value="X"> X
    </label>
    <label>
        <input type="checkbox" value="A"> A
    </label>
    <label>
        <input type="checkbox" value="A A" class="default"> A A
    </label>
    <label>
        <input type="checkbox" value="A B" class="default"> A B
    </label>
    <label>
        <input type="checkbox" value="F" checked="true"> F
    </label>
    <label>
        <input type="checkbox" value="E" checked="true"> E
    </label>
</div>

To achieve the sorting of the label elements can use the sort() method, providing your own function which defines the sorting logic to place the .default checkboxes first, then those which are checked, and then not checked, with each sub section ordered by the value of the checkbox. Once the sorting is complete you can search for the last .default and :checked elements and add an hr after them. Something like this:

function sortGiveNamesFilter() {
    $('#subfilterNamesContainer label').sort(function(a, b) {
        var $a = $(a).find(':checkbox'),
            $b = $(b).find(':checkbox');

        if ($a.hasClass('default') && !$b.hasClass('default'))
            return -1;
        else if (!$a.hasClass('default') && $b.hasClass('default'))
            return 1;

        if ($a.is(':checked') && !$b.is(':checked'))
            return -1;
        else if (!$a.is(':checked') && $b.is(':checked'))
            return 1;

        if ($a.val() < $b.val())
            return -1;
        else if ($a.val() > $b.val())
            return 1;

        return 0;
    }).appendTo('#subfilterNamesContainer');

    $('#subfilterNamesContainer .default:last, #subfilterNamesContainer :checked:last').closest('label').after('<hr />');
}

Working example

Note that the JS code can be made shorter with the use of ternary expressions, I just kept it verbose to make it obvious how it was working.


Post a Comment for "How To Sort Checkboxes By Class, Value, And Checked"