Tuesday, June 7, 2011

How to get checkboxlist selected item values on client side using javascript

Sometimes, you may need to find out server side checkboxlist selected item values on client side.By default checkboxlist does not send item value to the client.This problem can be solved by assigning values to each item of checkboxlist in page load event as shown below

protected void Page_Load(object sender, EventArgs e)
{
foreach (ListItem li in cblListItems.Items)
li.Attributes.Add("mainValue", li.Value);
}

Then call the below javascript function on click of checkboxlist.

function GetCheckBoxListValues(chkBoxID)
{
var chkBox = document.getElementById(chkBoxID);
var options = chkBox.getElementsByTagName('input');
var listOfSpans = chkBox.getElementsByTagName('span');
for (var i = 0; i < options.length; i++)
{
if(options[i].checked)
{
alert(listOfSpans[i].attributes["mainvalue"].value);
}
}
}

No comments:

Post a Comment