Jquery returns 'UNDEFINED', trying to get the value of a text field (asp.net)

While I am trying to get the value of a text field with .val (), it always shows 'undefined'. Below is the code I'm using. Please help me with friends.

<asp:TextBox runat="server" ID="txtComment" Width="650" /> <asp:Button runat="server" ID="btnSubmitComment" Text="Submit" /> $(document).ready(function () { $('input[id$=btnSubmitComment]').click(function () { var comment = $("#txtComment").val(); alert(comment); }); 
+4
source share
3 answers

One standard asp.net way is to get the display identifier and use it in javascript like:

 $(document).ready(function () { $('#<%=btnSubmitComment.ClientID%>').click(function () { var comment = $('#<%=txtComment.ClientID%>').val(); alert(comment); }); 

(from the moment you go with the identifier, and don't use any other way to select controls like css, type, etc.

+1
source

asp.net loads the id element. It looks like you are using it in a click statement. Have you tried this?

 $(document).ready(function () { $('input[id$=btnSubmitComment]').click(function () {//you are using the [id$=] selector here. var comment = $("input[id$=txtComment]").val();//use it here too alert(comment); }); 

Or you can use <%= txtComment.ClientID %> , but I personally never used it. I believe that you need to tell asp.net to insert JavaScript files on the page so that the client side id is placed in the right places. I will look for a link for this potential solution.

+5
source

This is normal when .net displays HTML, the texbox id becomes something like ct_001_txtComment.

  • You can add a css class and get the value from the class.
  • Or you can change the following parameter in web.config to make static identifiers in the page element

    controlRenderingCompatibilityVersion="4.0" clientIDMode="Static"

  • Or you can get it from the client ID as follows: <% = txtComment.ClientID%>

+3
source

Source: https://habr.com/ru/post/1445505/