Introduction
I needed a script to check/uncheck all the items in CheckBoxList in a gridview, but all the search lead to the use of two controls, one for the Select All and the other for the List itself.
Using the Code
I'll assume that the CheckBoxList already has items.
We will add attribute to each checkbox in the checkboxlist.
C#
foreach (ListItem item in chkList.Items)
{
item.Attributes.Add("onclick", "CheckStatus(this)");
item.Selected = true;
}
JavaScript
function CheckStatus(chk) {
$(document).ready(
function () {
var chkList = $($(chk).parents('table')).first();
var firstCHK = $(chkList).find(':checkbox').first();
if ($(firstCHK).attr('value') == 0) {
if ($(firstCHK).attr('value') == $(chk).attr('value')) {
$(chkList).find(':checkbox').each(function () {
this.checked = $(firstCHK).is(':checked');
});
}
else {
if ($(chk).is(':checked') == false) {
$(firstCHK).attr('checked', false);
}
else {
var flag = true;
$(chkList).find(':checkbox').each(function () {
if (this.checked == false && this.value != 0)
flag = false;
});
$(firstCHK).prop('checked', flag);
}
}
}
});
}