As Darin Dimitrov said in his answer:
<%= txtTest.ClientID %>
should work but not in a separate javascript
file where server side scripts do not execute.
The solutions that I could find for those are:
<input runat="server" id="txtTest" value="test" class="txtTest" />
Using class you can retrieve the value anywhere. This is one of the best solutions (usually the best)
var value = $('.txtTest').val();
- Use
ClientID
code in the aspx
You can always call ClientID
in the aspx, but if you are working with some kind of structure, this isn't the best solution. I like to use this method when I'm testing something.
var value = $('#<%=txtTest.ClientID%>').val();
You can also use ClientID
in a external js file with a workaround. IT'S NOT PRETTY, use only if you really need it. I usually do this when I use Telerik
.
In the aspx:
var id = <%=txtTest.ClientID%>;
In the js file:
var value = $('#'+id).val();
so the HTML becomes
<input runat="server" id="txtTest" value="test" ClientIDMode="Static" />
and the js can call it as it is named of
var value = $('#txtTest').val();
The problem with this solution is that you need to be very careful to avoid duplicity on the ids
of your page. Try never use Static
mode in a controller.
As states MSDN:
The ClientID value is set to the value of the ID property. If the
control is a naming container, the control is used as the top of the
hierarchy of naming containers for any controls that it contains.
The link of shaans's answer is a awesome place to check extra information about ClientIDMode.
Cleaner HTML Markup with ASP.NET 4 Web Forms - Client IDs (VS 2010 and .NET 4.0 Series)