One of the worst controls in the ASP.NET library is the CheckBoxList (or the RadioButtonList). I just can't understand why they have implemented it the way they did. The thing that annoys me the most is that it doesn't render the value of each item in the list in the HTML code. I will describe a workaround for this in this post.
Let's start by creating a simple CheckBoxList:
<asp:CheckBoxList ID="MyCheckBoxList" RepeatLayout="Flow" runat="server">
<asp:ListItem Text="One" Value="1" />
<asp:ListItem Text="Two" Value="2" />
</asp:CheckBoxList>
This is the generated HTML code:
<span id="ctl00_MyCheckBoxList">
<input id="ctl00_MyCheckBoxList_0" type="checkbox" name="ctl00$MyCheckBoxList$0" />
<label for="ctl00_MyCheckBoxList_0">One</label><br />
<input id="ctl00_MyCheckBoxList_1" type="checkbox" name="ctl00$MyCheckBoxList$1" />
<label for="ctl00_MyCheckBoxList_1">Two</label>
</span>
Note that no value attribute is generated for the input elements even though we specified a value.
If you try to add it as an attribute nothing will happen. This will generate the same HTML code:
foreach (ListItem li in MyCheckBoxList.Items)
{
li.Attributes.Add("value", li.Value);
}
However, if we change the attribute to something else than value a span will be added to wrap the input checkbox element.
foreach (ListItem li in MyCheckBoxList.Items)
{
li.Attributes.Add("id", li.Value);
}
This is the generated HMTL code:
<span id="ctl00_MyCheckBoxList">
<span id="1">
<input id="ctl00_MyCheckBoxList_0" type="checkbox" name="ctl00$MyCheckBoxList$0" />
<label for="ctl00_MyCheckBoxList_0">One</label>
</span><br />
<span id="2">
<input id="ctl00_MyCheckBoxList_1" type="checkbox" name="ctl00$MyCheckBoxList$1" />
<label for="ctl00_MyCheckBoxList_1">Two</label>
</span>
</span>
This is really odd but now we can at least access the checkbox value on the client side. You could do it like this with jQuery:
$("#<%= MyCheckBoxList.ClientID %>").find(":checkbox").click(function () {
alert($(this).parent().attr("id"));
});
Or with ASP.NET AJAX:
var checkBoxList = $get("<%= MyCheckBoxList.ClientID %>");
var checkBoxes = checkBoxList.getElementsByTagName("input");
for (var i = 0; i < checkBoxes.length; i++) {
$addHandler(checkBoxes[i], "click", function () {
alert(this.parentNode.id);
});
}