Bill Robertson's Blog

My way to assign "for" attribute on labels

I've been carrying this control around for a while.  Mostly because I built this on an early version of MS Ajax, back when it was still called Atlas.  I've finally updated it to MS Ajax RTM.  My friend Neils is an avid accessibility guy.  He was frustrated by the manner in which he had to wire up labels with their associated input control.

The issue brings itself up when you are using master pages, user controls...basically any control that implements INamingContainer.  To wire up the for attribute to the correct ID you must either:

You can make the label runat="server" taking up server side resources.

<label runat="server" for="FirstName">First Name: </label>
<asp:TextBox id="FirstName" runat="server" />

or you can inject the generated ClientID from the control into the label element.  Also using up server side resources.

<label for="<%=FirstName.ClientID %>">First Name: </label>
<asp:TextBox ID="FirstName" runat="server" />

Using the BillRob.WebControls.LabelAutoAssigner control will allow you to not use any server resources to wire up any labels.  You simply give the for attribute the value that the control has on the page.  For example

<label for="FirstName">First Name: </label>
<asp:TextBox id="FirstName" runat="server" />

Notice there is no runat="server" attribute.  When the page is loaded at the browser the LabelAutoAssigner does its magic.  It finds every <label> control on the page and checks its htmlFor attribute.  (notice in javascript it's htmlFor and not for.)  It first checks for sibling <input>, <select>, or <textarea> tags and checks to see if the client ID ends with its htmlFor attribute.  In the case above, it will look for an id ending with "_FirstName". 

It then walks up each parentNode and checks the children.  If it hits the root of the document nothing happens and the algorithm jumps to the next label.

INSTRUCTIONS FOR USE

1. Drop the BillRob.WebControls.dll into your bin directory.
2. Register the dll for page consumption.
    Either in the web.config
    <system.web>
        <pages>
            <controls>
                <add tagPrefix="BillRob" namespace="BillRob.WebControls" assembly="BillRob.WebControls"/>
            </controls>
        </pages>
    </system.web>
    Or on the page itself.
        <%@ Register TagPrefix="BillRob" Namespace="BillRob.WebControls" Assembly="BillRob.WebControls" %>
3. Drop the control on a page. You should place on your master page. It can be placed more than once and it will only execute once. Also if there are no labels on the page, no ill will befall.

    <BillRob:LabelAutoAssigner ID="Assigner" runat="server" />

I'm open for suggestions on this or if you find a specific pattern that this control doesn't handle, let me know and I'll get it updated.

Leave a Comment

(required) 

(required) 

(optional)

(required)