ASP.NET: Creating an accessible label
From Wiki
Summary: Creating an accessible label
If you create a label on your page e.g.
- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
it will render in the user's browser as a span tag:
- <span id="Label1">Label</span>
However, labels are often used as a means of showing text next to another control e.g.
- <asp:Label ID="Label1" runat="server" Text="Enter Text:"></asp:Label>
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
However, the label will still render as a span tag so this isn't very good for accessibility. If we modify the above example to utilise the AssociatedControlID property of the Label then we can modify how the label is rendered. So, if we now use:
- <asp:Label ID="Label1" runat="server" Text="Enter Text:" AssociatedControlID="TextBox1"></asp:Label>
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
you will see the output has changed to:
- <label for="TextBox1" id="Label1">Enter Text:</label>
- <input name="TextBox1" type="text" id="TextBox1" />
This makes the HTML much more accessible as it will tell text readers why the label is there, and it will allow standard browser users to click anywhere in the textbox or the label to give that control focus.
This Hack is part of the ASP.NET Hacks collection


