Posts Tagged ‘CheckBoxList and Javascript’

Today I have spend lot of time to get the values of each item of CheckBoxList using javascript. And finally I got success.

What I want to do is:

I have one CheckBoxList control that binds values at runtime from the database, and when I click on a button from the page, I want to get the values (Database Primary Key) from the CheckBoxList, but for the checked checkboxes only.

Here is the code, what I have achieved so far. This code works fine with IE 7, but I am not sure with the FireFox.

ASPX page: <asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound" >
<asp:ListItem Value="First1" Text="First" ></asp:ListItem>
<asp:ListItem Value="second2" Text="Second"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<script language="javascript" type="text/javascript">
function CheckItem()
{
var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>').childNodes[0];
for(var i=0; i<tbl.childNodes.length;i++)
{
for(var k=0; k<tbl.childNodes[i].childNodes.length; k++)
{
if(tbl.childNodes[i].childNodes[k].nodeName == "TD")
{
var currentTD = tbl.childNodes[i].childNodes[k];
for(var j=0; j<currentTD.childNodes.length; j++)
{
if(currentTD.childNodes[j].nodeName == "SPAN")
{
var currentSpan = currentTD.childNodes[j];
for(var l=0; l<currentSpan.childNodes.length; l++)
{
if(currentSpan.childNodes[l].nodeName == "INPUT" && currentSpan.childNodes[l].type == "checkbox")
{
var currentChkBox = currentSpan.childNodes[l];
if(currentChkBox.checked)
{
alert(currentSpan.alt);
}
}
}
}
}
}
}
}
}
</script>

Code Behind:

Button1.Attributes.Add("onclick", "javascript:CheckItem();");
CheckBoxList1.DataSource = <Your Dataset>;
CheckBoxList1.DataTextField = "PersonName";
CheckBoxList1.DataValueField = "PersonID";
CheckBoxList1.DataBind();
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList chkList = (CheckBoxList)(sender);
foreach (ListItem item in chkList.Items)
{
item.Attributes.Add("alt", item.Value);
}
}

Advertisements