views:

3220

answers:

3

I've got a bunch of checkboxes generated by an asp.net CheckBoxList control. I want to get the text the user sees next to the control on the page.

With similar controls, like RadioButtonList, I've been able to get their values in jQuery by doing this:

var selected = $("input:checked[id*='" + Control.id + "']");

and then looping through and getting the value:

var whatIwant = selections[i].value;

(In this case, that "value" will be the text I want).

But - CheckBoxList renders differently. For each ListItem there's not only the input, but an html tag like so:

<input id="ctl00_ContentPlaceHolder1_ConsultedList_0" type="checkbox" name="ctl00$ContentPlaceHolder1$ConsultedList$0" />
<label for="ctl00_ContentPlaceHolder1_ConsultedList_0">Other service providers</label>

As you can see, the input tag itself, which is what my nice little jQuery query finds, doesn't include the info I want: "Other service providers". That's on the label tag.

Can anyone think of a good solution for this - maybe a good way of making the CheckBoxList render the text I need in the input tag, or some clever jQuery to find the labels that correspond to the selected inputs?

+1  A: 

Try using Control.ClientID.

ChaosPandion
+2  A: 

You can use the selector you are already using (but just use the clientId), then get the next sibling (the label) and get its text value

e.g

$("#" + Control.ClientId).next().text();

Or you can just get the label by using its for attribute

$("label[for=" + Control.ClientId + "]").text();
redsquare
Thanks, using .next() like that was exactly what I needed.
MGOwen
+1  A: 

You will have to iterate over your form elements, searching for the label and grab its inner text, ASP .NET wraps the checkboxes inside a table with the ClientID of the control, you can use a selector like the following:

  var selection = [];
  $('#<%= CheckBoxList.ClientID %> :checked').each(function () {
    selection.push($(this).next('label').text());
  });

The HTML rendered by ASP .NET for CheckBoxLists looks like this:

<table id="check1" border="0">
    <tr>
     <td><input id="check1_0" type="checkbox" name="check1$0" />
                <label for="check1_0">Item 1</label></td>
    </tr><tr>
     <td><input id="check1_1" type="checkbox" name="check1$1" />
                <label for="check1_1">Item 2</label></td>
    </tr>
  .....
</table>

You can check an example with ASP .NET generated markup here.

CMS