Get Asp.Net TextBox or Label value using JavaScript

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

Get TextBox value:


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 javascript using the below code

var name = document.getElementById("<%=txtName.ClientID %>").value;

Get Label value :


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 javascript using the below code

var name = document.getElementById("<%=lblName.ClientID %>").innerHTML;

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 getElementById("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 javascript.

For more posts on Javascript visit: javascript

2 comments:

  1. try this...

    document.getElementById("ctl00_ContentPlaceHold_txtName").value;

    ReplyDelete
  2. One could also set the ClientIDMode="Static" in textbox attribute. It will then render the input tag with the ID as specified.

    ReplyDelete