When I create a form, I try to make accessibility a top priority, but the output from asp .NET negates some of this. For example, when I set a label tag for an input tag, I create it a such:
<label for="frmFirstName">First Name<span class="required">*</span></label>
<asp:TextBox id="frmFirstName" CssClass="textbox" runat="server" />
But, when the HTML is output from the page, it is output as:
<label for="frmFirstName">First Name<span class="required">*</span></label>
<input name="ctl00$phMainContent$frmFirstName" type="text" id="ctl00_phMainContent_frmFirstName" class="textbox" />
This is a problem, as now the label is no longer tied to the input element. Is there a way to force .NET to output the exact id I set for the input field? I shouldn't have to use Javascript to correct something like this.
You can use the
ClientId
property. This is what will be output as the control Id in HTML and what you can use client side to reference the rendered element:Note:
<%:%>
is new with ASP.NET 4.0 - you will need to use<%=%>
if on .NET 3.5 and before.Edit:
Just to add that
ClientId
is the way to go when referencing the control from Javascript.Use the
asp:Label
element and point itsAssociatedControlId
property to your textbox.That should output the correct HTML for you.
In addition to the AssociatedControlId and <%= control.ClientId %> solutions, if your control (in this case, "frmFirstName") is guaranteed to be the only control with that ID on the page, then you can set the ClientIDMode property of the control to "Static", which will mean that ASP.NET will not munge the ID in the rendered HTML.
For example:
will render as
This will also make it easier if you happen to need to refer to it from Javascript, since it can be a pain to render ASP.NET's auto IDs in Javascript (as far as I know, it's impossible to do in a seperate .js file, you'd need to embed the JS on the page and use <%= control.ClientID %>).
See more about ClientIDMode here: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
If you use ASP.Net 4 you can set the ClientIDMode attribute of the control to
static
. This will let it keep the value of the ID tag when rendered.