lundi 22 février 2016

A proper select all checkbox in a grid header

I've inherited a new project and my jQuery skills are extremely weak. I'm looking to create a select all checkbox for a table.


The background:

The table exists with a column for checkboxes. As part of the header row, there's a checkbox called "Select All" that doesn't perfectly function. You can press it and it will select all, but it will "sort" a few items (for no reason) and the box will uncheck itself when finished. This makes things difficult. Code clip:

<thead class="KoTableTH">
    <tr data-bind="click: sort">
        <th>
            <input type="checkbox" id="cbSelectAll1" />Select All
        </th>
        <th id="FirstName">First Name</th>
        <th id="LastName">Last Name</th>
        <th id="PhoneNumber">PhoneNumber</th>
    </tr>
</thead>

And a clip of jQuery:

$("[id*=cbSelectAll1]").live("click", function () {
    var grid = $(this).closest("table");
    $("input:checkbox", grid).each(function () {
        if (chkHeader.is(":checked")) {
            $(this).attr("checked", "checked");
            $("td", $(this).closest("tr")).addClass("selected");
        } else {
            $(this).removeAttr("checked");
            $("td", $(this).closest("tr")).removeClass("selected");
        }
    });
});

Attacking a solution

So my first idea is to somehow lock down the check state at the end to no avail. Then I removed the data-bindings from the Select All for giggles and it still doesn't stick. So an unbound checkbox doesn't stay checked. I then moved on to try removing the checkbox from the table, but I can't figure out how to properly define the var grid above, as var grid = $('#checkableGrid') is not a valid definition or something as it fails silently.

Conclusion

I think I understand the problem but no idea how to put together a solution. Putting a checkbox in a sortable header is probably not the best way to go about things, but this is my burden I've inherited.




Aucun commentaire:

Enregistrer un commentaire