Search code examples
sortingknockout.jsknockout-2.0

knockout - Bring checked checkboxes on top of the list using foreach


<div data-bind="foreach: lists">
    <div class="checkbox list-item">
        <label>
            <input type="checkbox" data-bind="checked: isSelected, click: $parent.list, disable: $parent.disableInput()"/> <span data-bind="text: note">
        </label>
    </div>
</div>

I tried to do the checked checkboxes to move on top. When I click the unchecked checkbox, it needs to move on top. When I click the checked checkbox, it needs to move back down.


Solution

  • You're going to need an intermediate object to hold the sorted list. Something like:

    const sorted_lists = ko.pureComputed(() => {
        return lists.sort(a => a.isSelected ? -1 : 0);
    });
    

    Then you point your foreach to this computed value: <div data-bind="foreach: sorted_lists">...