Get/Set CheckBoxList values using Javascript in ASP.NET

Some times we need CheckBoxList values in Javascript code(For example to select all or clear all in CheckBoxList). Here is described how can we performed client side operations on Asp.net CheckboxList control.

Let's assume our webform contains a CheckBoxList named chkTest,

<asp:checkboxlist id="chkTest" onclick="CheckItem(this)" runat="server" Width="500px" RepeatDirection="Horizontal" RepeatColumns="2" > </asp:checkboxlist>

as you can see I've put a javascript code when triggers click on checkboxlist. You don't have to...
Javascript function called CheckItem contains this script :



function CheckItem(checkBoxList)
{

var options = checkBoxList.getElementsByTagName('input');
var arrayOfCheckBoxLabels= checkBoxList.getElementsByTagName("label");
document.getElementById("hdnSutunlar").value="";
for(i=0;i<options.length;i++)
{
var opt = options[i];
if(opt.checked)
{
document.getElementById("hdnSutunlar").value = document.getElementById("hdnSutunlar").value+arrayOfCheckBoxLabels[i].innerText+":";
}
}

}




as you can see with arrayOfCheckBoxLabels[i].innerText property we can get selected list item value. In my code every click on my checklist causes adding checked item value into a hidden area.I used it different purpose.I hope it wouldn't gets harder to understand.


In addition .Net renders checkboxlist as a html <tr><td><input><label for> </.... you can't get item text and item value properties seperately with Javascript.You can get only item text properties with js.



Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript




function CheckBoxListSelect(cbControl, state)
{
var chkBoxList = document.getElementById(cbControl);
var chkBoxCount= chkBoxList.getElementsByTagName("input");
for(var i=0;i<chkBoxCount.length;i++)
{
chkBoxCount[i].checked = state;
}

return false;
}


And in listitem set onclick event
onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',true)"

I hope it helps you.

No comments:

Post a Comment