Sunday, February 8, 2009

Loop through CheckBoxList Control in Javascript

In this post i will show you how you can access each checkBoxList Item in javascript. Here is small piece of javascript code you can use to loop through the CheckBoxList control.
function CheckAllCheckBoxListOption()
{
var checkBoxList = document.getElementById("<%=CheckBoxList.ClientID %>");
if(checkBoxList !=null)
{
var chkCheckBoxListItems= checkBoxList.getElementsByTagName("input");
for(var intCounter=0;intCounter<=chkCheckBoxListItems.lenght-1 ; )
{
if
(chkCheckBoxListItems[intCounter].checked)
// Item is selected
else
//Item is not selected by user
intCounter= intCounter+1;
}

}
}

In the code above what i have done is to get the checkBoxList control which i want to loop through, by using the document.getElementById and passing the checkboxList control Client Id so if you used the master page in your project then the actual id of the code is passed which also contain the master page prefix. Main statement of this small code snip is to get the ListItem from the checkBoxList which i did't by checkBoxList.getElementsByTagName("input"), using this statement i have store the number of listitem in the chkCheckBoxListItems which hold the array of the CheckboxList Items and then we can use this array variable and check the each ListItem and check whether the list Item is checked or not.

All and any comments / bugs / suggestions are welcomed!


4 comments:

Anonymous said...

how can we access the Text of the current checkBoxList Item??

Asim Sajjad said...

By Using the following statement you can access the text of the current CheckBoxList item text when looping through the ListItem
chkCheckBoxListItems[intCounter].nextSibling.innerHTML

Anonymous said...

chkCheckBoxListItems.lenght-1
should be

chkCheckBoxListItems.length-1

but other than that... thanks VERY VERY MUCH!

Ravi Gupta said...

This helped me. Thanks