This is a common task that I searched high and low for but ended up coding
along with some pieces from here and there. All I wanted was to have a
group of checkboxes with one being a "select all" that would, naturally, select
all others in its group when selected and un-select them when it was
un-selected. My first pass was to use a checkbox list since they were
going to be bound to an ArrayList and then have one stand alone check box to use
for "all" that would fire an event to iterate through the others. That
required a trip to the server plus some groups have a built-in selection that is
equivalent to "all"...that left me with the chance to have two "all"
checkboxes.
So I decided to use a DataList and a client-side function. I have one
HtmlInputCheckbox in the DataList and I use the OnItemDataBound event and add an
"OnClick" attribute for box that represent "all" for that group.
Here's the DataList in the aspx page. I'm using the field from
the ArrayList as both the value and display text here.
<asp:DataList ID="dataList" OnItemDataBound="DataList_ItemDataBound" Runat=server>
<ItemTemplate >
<input type=checkbox id="chkBox" name="chkBox" runat=server
value='<%# Container.DataItem %>'><%# Container.DataItem %>
</ItemTemplate>
</asp:DataList>
Here is the DataList_OnItemDataBound
event handler in the code-behind.protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlInputCheckBox chkData = (HtmlInputCheckBox)e.Item.FindControl(chkBox);
if(chkData.Value.ToLower() == "all")
{
chkData.Attributes.Add("onclick", "CheckAll(this,'" + chkData.Name + "');");
}
}
}Here's the client-side javascript function in the aspx
page.<script language=JavaScript>
function CheckAll(checkAllBox, fieldName)
{
var frm = document.Form1;
var actVar = checkAllBox.checked;
for(i = 0; i < frm.length; i++)
{
e = frm.elements[i];
if (e.type == 'checkbox' && e.name.indexOf(fieldName) != -1)
e.checked = actVar ;
}
}
</script>