In this tutorial I will show you how to check and uncheck all checkboxes using javascript. I was assigned this task so I decided to write a tutorial on it.
Scenario:-
Let’s start with a scenario where we have a gridview in which there is a column Enable/Select All Option (checkbox to check all options). When select all checkbox in header row is checked all checkboxes in the gridview under the same column should be checked and when user uncheck select all checkbox in the header row all the checkboxes in the same column of the gridview should be unchecked.
Header Row Checkbox HTML:-
<asp:CheckBox ID="chb_SelectAll" Text="Select All" runat="server" Enabled="true" AutoPostBack="false" Style="font-size:11px;" onclick="CheckAll(this);"/>
Javascript Function:-
function CheckAll(Checkbox) {
// By using the gridview id = GridView1
var GridVwObj = document.getElementById("<%=GridView1.ClientID %>");
// Using for loop on gridview object. started loop from i=1 because we need to skip header row.
for (i = 1; i < GridVwObj.rows.length; i++) {
// Cells[0] shows that checkboxes are in first column so you can give any column where you have checkboxes i.e cells[1],celss[2]...etc.
GridVwObj.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;
}
}
Note:- I have used GridView having ID = GridView1, if you are using simple html table having id = table1 then you need to replace this document.getElementById("table1"); line in above function and you are good to go.
Jquery Function:-
By using jquery first we need to give a class attribute to every checkbox in the table. E.g. I have used .checkboxClass in this case
Method 1:-
function CheckAll(ref) {
if ($(ref).checked) {
$('.checkboxClass').each(function () { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkboxClass"
});
} else {
$('.checkboxClass').each(function () { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkboxClass"
});
}
}
Method 2:-
$('input[id$=chb_SelectAll]').click(function (event) { //on click
// this will represent chb_SelectAll check select status
if (this.checked) {
$('.checkboxClass').each(function () { //loop through each checkbox
this.checked = true; //select all checkboxes with class "checkboxClass"
});
} else {
$('.checkboxClass').each(function () { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkboxClass"
});
}
});
No comments:
Post a Comment
Please do not enter spam links.