Getting id from asp.net server runat server in jQuery

I am trying to do some things in jQuery using ASP.NET. But the identifier from runat="server"does not match the identifier used in HTML.

I used this to get the identifier from this situation:

$("#<%=txtTest.ClientID%>").val();

But in this case it will not work. I do not know why.

Javascript

/* Modal */
function contatoModal() {
    //alert("Test");
    alert($("#<%=txtTest.ClientID%>").val());
}

HTML

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

Any tips?

+5
source share
7 answers

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

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

and then:

var value = $('.txtTest').val();
+17
source

, jQuery, . jQuery . , , "ends with" .

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

- ( ):

<input id="ctl00_contentplaceholder_txtText" />

:

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

.

+3

:

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

$(txtTestID).val();

, <%= . , .

+2

WebForm/HTML-....

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

JQuery

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

100% , ....

+2

:

<%= txtTest.ClientID %> , javascript , .

, :

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

  • class ID

. ( )

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

  • ClientID aspx

ClientID aspx, - , . , - .

var value = $('#<%=txtTest.ClientID%>').val();

ClientID js . IT NOT PRETTY, , . , Telerik.

aspx:

var id = <%=txtTest.ClientID%>;

js:

var value = $('#'+id).val();

HTML

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

js ,

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

, , ids . Static .

MSDN:

ClientID ID. - , , .


shaans answer - ClientIDMode.

HTML- - ASP.NET 4 - ( VS 2010 .NET 4.0)

+1
source

To avoid problems with display identifiers, use a class instead. This will not change during rendering:

function contatoModal() {

//alert("Test");

alert($(".txtTest").val());

}

HTML:

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

All Articles