Monday, January 25, 2010

Accessing check box list items in java script

Most of the time we need to access check box item lists in javascript for various purpose during client side validation or to clear the checked items of the check box list. Normally we get the clientId of the control by below syntax
var controlClientID = document.getelementbyid(controlID.ClientID);
When the control is a check box list (or radio button list) we can get only the client ID of the check box list (or radio button list) and not all the check box list items. Normally check box list items clientID's are of the format CheckBoxList.ClientID_0 or _1 ... and this continues till the number of items in check box list.

Suppose there are 3 check box items in a check box list. And let the client id of the check box list is xxxxxx.
Then the check box items client ids will be xxxxxx_0, xxxxxx_1, xxxxxx_2.
So first we have to find the client id of the check box list then the count of the check box items. Then append with "_" and then count to get the items client id. Once you get the client id of items one can easily operate further either to select a special check box item or to deselct all the check box items.
Here i will explain to uncheck all the items of the chekc box list on a button click like clear form.
Let the id of the check box is chkBoxList
var checkBoxListCtrlId = document.getelementbyid(chkBoxList.ClientID);
var itemsCount = number of itmes in the check box list.
for(i = 0; i < itemsCount; i++)
{
if(document.getelementbyid(checkBoxListCtrlID + "_" + i) != null)
{
document.getelementbyid(checkBoxListCtrlId + "_" + i).checked = false;
}
}

This way one can process other lists like radio button ist and drop downlist etc.