Getting ID from asp.net runat server in jQuery

Solution 1:

<%= txtTest.ClientID %> should work but not in a separate javascript file where server side scripts do not execute. Another possibility is to use a class selector:

<input runat="server" id="txtTest" value="test" class="txtTest" />

and then:

var value = $('.txtTest').val();

Solution 2:

As others have mentioned, you can pass a class selector to jQuery, but that is a bit messy. I prefer to use the jQuery attribute ends with selector. Given that a generated ID is a flattened hierarchy of controls, you can use the "ends with" selector to find your element.

<input runat="server" id="txtText" />

When rendered, the generated ID becomes something like this (if within a masterpage's content place holder):

<input id="ctl00_contentplaceholder_txtText" />

To find this control:

$("input[id$='txtText']")

Take caution when using this within a repeater.

Solution 3:

In WebForm / HTML Page....

<asp:TextBox ID="txtUserName" runat="server" Class="form-control"></asp:TextBox>  

In Jquery

var UserName = $("[id*=txtUserName]").val();
alert(UserName);

100% Sure its Working for me....

Solution 4:

Try putting it into a variable name:

var txtTestID = '#' + '<%=txtTest.ClientID %>';

$(txtTestID).val();

I'm not sure if the <%= likes being inside double quotes. I've always had mixed behaviors when not using the single quote.