Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery returning 'UNDEFINED' while trying to get the value of textbox (asp.net)

While I am trying to get the value of textbox with .val(), Its always showing 'undefined'. Below is the code i am using. Please help me out 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);
});
like image 487
Arpit Gupta Avatar asked Jan 16 '23 01:01

Arpit Gupta


2 Answers

asp.net pads the element's returned id. Looks like you are using it in the click statement. Did you try 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 have never used it. I believe that you need to tell asp.net to embed JavaScript files into the page, so that the client side id gets placed in the proper places. I will look for a link for this potential solution.

like image 107
JoeFletch Avatar answered Jan 23 '23 04:01

JoeFletch


That's normal, when .net renders HTML the texbox's ID become something like ct_001_txtComment.

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

    controlRenderingCompatibilityVersion="4.0" clientIDMode="Static"

  • Or you can get it from the Client ID like this: <%=txtComment.ClientID%>

like image 27
MatthewK Avatar answered Jan 23 '23 04:01

MatthewK