See my other post, which explains "how to set the value attribute for a single check box through c# code" before proceed to this post.
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:
foreach (ListItem li in checkBoxList.Items)
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:
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:
$("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {
var currentValue= $(this).parent().attr('someValue');
if(currentValue != '')
values += currentValue + ",";
});
So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated. I think, now you got an idea of how to access the values in client-side. Hope it will help you to understand what I am trying to say. Please add your valuable comments on it.
No comments:
Post a Comment