Get Asp.Net TextBox or Label value using JQuery

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using Jquery.

Get TextBox value with jquery:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using JQuery using the below code

var name = $("#<%=txtName.ClientID %>").val();

Get Label value with jquery :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using JQuery using the below code

var name = $("<%=lblName.ClientID %>").html();

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write $("#txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using JQuery.

For more posts on JQuery visit: JQuery

3 comments:

  1. If using Code Behind is considered a best practice, why are we encouraging people to place Javascript/Jquery directly into their page. It defeats the entire purpose of separating code from content.

    Using an external javascript file will not allow you to use this method. And yet, virtually every example on the web today shows this particular method.

    Beginning with ASP.Net 4, you can simply set the ClientIDMode of an asp.net control to "static" and you don't have to worry (usually) about this issue. And then put your code off the content page as the asp.net folks, rightly, intended.

    Very simply:

    <asp:TextBox ID="textboxExample" runat="server" ClientIDMode="Static" />

    then the script becomes...

    To set it:

    $('#textboxEample').val("I've been set!");

    To get it...

    var WhatThe = $('#textboxExample').val();

    I recognize that if you're not using ASP.NET 4 or higher, then this is a problem, but for me, it was worth moving to 4 just to get this one particular feature so I could clean up my content pages, and have less risk of "inexperienced" users who are responsible for content, screwing up my code. Just my two cents.

    This doesn't cover every permutation, but it gets a lot of them.

    ReplyDelete
    Replies
    1. Hi Rob,

      First of all thank you very much for your valuable comment. Yes, we can use ClientIDMode="Static" to get the same ID in browser. Thanks for mentioning it :-)

      Ranadheer

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete