Thursday, October 7, 2010

SELECT ALL \ DESELECT FUNCTIONALITY FOR CHECKBOX INSIDE GRIDVIEW

I have a GridView, in which my first column is Template Field which contains checkbox.

<asp:gridview id="grdTest" runat="server" autogeneratecolumns="false" datakeynames="TestID">
<columns>
<asp:templatefield>
<headertemplate>
<asp:checkbox id="ChkAll" runat="server" />
</headertemplate>
<itemtemplate>
<asp:checkbox id="chkRequest" runat="server" />
</itemtemplate>
<asp:boundfield datafield="Name" headertext="Name" />
</asp:TemplateField>
</columns>
</asp:GridView>

Now, I want on click of ChkAll checkbox (which is in header of grid) all the checkboxes in the first row gets selected. Also, when I deselect any checkbox in first row, ChkAll checkbox gets deselected.

I did this using jquery :

<script type="text/javascript">
$(document).ready(function () {
//To Select/Deselect all checkboxes on click of ChkAll checkbox.
var chkBox = $("input[id$='ChkAll']");
chkBox.click(
function () {
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']")
.attr('checked', chkBox.is(':checked'));
});

// To deselect CheckAll when a GridView CheckBox is unchecked.
$("#<%=grdTest.ClientID %> INPUT[type='checkbox']").click(
function (e) {
if (!$(this)[0].checked) {
chkBox.attr("checked", false);
}
});
});
</script>

No comments:

Post a Comment