Set a CSS class on an ASP.NET RadioButtonList ListItem

y0mbo picture y0mbo · Jul 1, 2009 · Viewed 41.4k times · Source

Is there any way to set a CSS class on an input item in a radio button list? I'd like to reference these form values by class in jQuery.

Given an ASP.NET RadioButtonList with classes set on the ListItems:

 <asp:RadioButtonList ID="RadioButtonList" runat="server">
      <asp:ListItem class="myClass" Text="Yes" Value="1" />
      <asp:ListItem class="myClass" Text="No" Value="0" />
 </asp:RadioButtonList>

Will render as:

 <span id="RadioButtonList" class="radioButtonListField myClass">
     <span class="myClass">
          <input id="RadioButtonList_0" type="radio" value="1" 
               name="RadioButtonList"/>
          <label for="RadioButtonList_0">Yes</label>
     </span>
     <span class="myClass">
          <input id="RadioButtonList_1" type="radio" value="0" 
               name="RadioButtonList"/>
          <label for="RadioButtonList_1">No</label>
     </span>
 </span>

Unfortunately, the "myClass" class is added to the <span> that contains the radio button item, not the <input> itself. How could I get it to look like this instead:

 <span id="RadioButtonList" class="radioButtonListField myClass">
     <span>
          <input id="RadioButtonList_0" class="myClass" type="radio" value="1" 
               name="RadioButtonList"/>
          <label for="RadioButtonList_0">Yes</label>
     </span>
     <span>
          <input id="RadioButtonList_1" class="myClass" type="radio" value="0" 
               name="RadioButtonList"/>
          <label for="RadioButtonList_1">No</label>
     </span>
 </span>

(This does not even get into the issue of adding the classes to dynamically bound RadioButtonLists.)

Answer

SolutionYogi picture SolutionYogi · Jul 1, 2009

Yes, RadioButtonList renders horrible HTML.

Anyway, it's still easy to get them from jQuery.

Try

$('span.myclass input:radio')

Above will get all the radio buttons inside the span with class 'myclass'.