Latest Entries »

Wednesday, March 16, 2011

Check/uncheck checkbox in table (GridView) with jQuery. Modern way.

Few moments ago I found a really preety and simple way to check/unckeck all input:checkbox inside GridView(table) column. I was really shocked!
And so you code:

.aspx
<asp:GridView ID="CmpJobOfferCandidatesGv" runat="server" AutoGenerateColumns="False"
 CssClass="EntityGridView">
 <Columns>
 <asp:TemplateField>
 <HeaderTemplate>
  <asp:CheckBox runat="server" ID="checkAllChb" />
 </HeaderTemplate>
  <ItemTemplate>
   <asp:CheckBox runat="server" ID="inviteToExamChb" style="width:20px;margin:0 auto;display:block;" />
  </ItemTemplate>
 </asp:TemplateField>
  <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="25px" />
 </Columns>
</asp:GridView>

.js
var chbClickEvent = function () {
    $('table[id*="CmpJobOfferCandidatesGv"] tr > td input:checkbox').each(function (index, Element) {
        $(this).trigger("click");
    })
}
$(document).ready(function () {
    $('input:checkbox[id*="checkAllChb"]').click(chbClickEvent);
});
                    

The magic above is caused because I trigger click event foreach checkbox in GridView Column instead of dealing with bunch of if statements to figure out state of checkbox.

$(document).ready(function () {
    $('input:checkbox[id*="checkAllChb"]').click(function () {
        $('table[id*="CmpJobOfferCandidatesGv"] tr > td input:checkbox').each(function (index, Element) {
            if ($(Element).attr('checked') == false) {
                $(Element).attr('checked', true);
            } else {
                $(Element).attr('checked', false);
            }
        });
    });
});

0 comments:

Post a Comment