Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

ASP.NET: Creating an accessible label

From Wiki

Jump to: navigation, search

Summary: Creating an accessible label

If you create a label on your page e.g.

  1. <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

it will render in the user's browser as a span tag:

  1. <span id="Label1">Label</span>

However, labels are often used as a means of showing text next to another control e.g.

  1. <asp:Label ID="Label1" runat="server" Text="Enter Text:"></asp:Label>
  2. <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:

  1. <asp:Label ID="Label1" runat="server" Text="Enter Text:" AssociatedControlID="TextBox1"></asp:Label>
  2. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

you will see the output has changed to:

  1. <label for="TextBox1" id="Label1">Enter Text:</label>
  2. <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

479 Rating: 5.0/5 (3 votes cast)