Thursday, June 28, 2012

ASP.NET Checkboxlist get values in client side [JQuery]

I know, this is the question most of the ASP.NET developers will ask or look for an answer on why there is no value attribute set for check box when it generates from the ASP.NET checkbox list? Where as the Radio button list, Drop down list and other controls has this value attribute set when you set the data source for them. But why there is no value attribute set for check box list control. Below is the nice explanation and will help you to understand the concept well.
If we assign some data source to the check box list control, then the HTML output is with two controls for each check box as input control with type checkbox and another is label with the text. So, This is the problem. How to get the value of the checkbox in client side using some javascript library? Here we need to think a way of how to set a attribute which holds the value for each checkbox and how to get it.
Below is the solution I found. In your C# code, after you bind the data source for the checkbox list, then need to add extra piece of code below to get our problem solved.
C# code:


  1. foreach (ListItem li in checkBoxList.Items)  
  2. li.Attributes.Add("someValue", li.Value);  
So, What happening here is, I am just adding extra attribute "someValue" for each check box in a check box list[checkBoxList] and looping through them and assign the actual value to that custom attribute. So that HTML for each checkbox on the page will render like this.
HTML rendered output:

  1. <span somevalue="8"><input id="ctl00_cpB_checkBoxList_0" name="ctl00$cpB$checkBoxList$0" type="checkbox"><label for="ctl00_cpB_checkBoxList_0">Testing</label></span>  
If you observe, there is an extra parent control for each check box control named <SPAN> with the attribute we have set in c# code for each checkbox. Now you have some value set with each checkbox and you can get it on client side easily. [There is no change in C# code accessing values.]
How to access the values on client side?
I am using JQuery, so I will give an example of how to get the values using the JQuery.
To get all checkboxes which are checked under a checkbox list are accessed as follows.
JQuery code:

  1. $("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {  
  2. var currentValue= $(this).parent().attr('someValue');  
  3. if(currentValue != '')  
  4. values += currentValue + ",";  
  5. });  
So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated

No comments:

Post a Comment