Thursday, July 5, 2012

Label for dynamically generated html input CheckBox Inside a ListView

Recently while testing one of the web pages on a Android phone the dynamically generated checkboxes inside a ListView was not working.This was happening because the ID of the checkbox did not match the for= attribute in the label tag.

The html when generated dynamically  will look something like this. Note the ID of the control ListView i.e “MobileTimeSlotListView” appended to the checkbox ID i.e. TimeSlotCheckBox below.
<span class="custom-time">
     <input name="MobileTimeSlotListView$ctrl0$TimeSlotCheckBox" type="checkbox" id="MobileTimeSlotListView_ctrl0_TimeSlotCheckBox" value="5/23/2012 10:30:00 PM" />
     <label for="TimeSlotCheckBox">May 23 - 10:30 PM - 11:00 PM</label>
<span class="box"><span class="tick"></span></span></span>

So to get around this I used a server variable for the label and tagged the checkbox ID as the associatedcontrolid

<span class="custom-time">
      <input type="checkbox" id="TimeSlotCheckBox" name="TimeSlotCheckBox" value='<%# Eval("PreviousTimeSlotsDate") %>' runat="server"/>
      <asp:label AssociatedControlID="TimeSlotCheckBox" runat="server" Text='<%# Eval("PreviousTimeSlotsString") %>'></asp:label>
<span class="box"><span class="tick"></span></span></span>

This will generate the below html wherein the ID of the checkbox will match the label for attribute value.

<span class="custom-time">
     <input name="MobileTimeSlotListView$ctrl0$TimeSlotCheckBox" type="checkbox" id="MobileTimeSlotListView_ctrl0_TimeSlotCheckBox" value="5/23/2012 10:30:00 PM" />
     <label for="MobileTimeSlotListView_ctrl0_TimeSlotCheckBox">May 23 - 10:30 PM - 11:00 PM</label>
<span class="box"><span class="tick"></span></span></span>

No comments: