How to Set/Get the value of Label Control in ASP.Net using jQuery

We can divide this question into 2 parts

  1. Set the value of Label control using jQuery
  2. Get the value of Label Control using jQuery

Before answering each of these questions, we can revisit some basics for better understanding

asp:Label is a server side ASP.Net control and resides at server side. When you request a page which contains Label control, ASP.Net converts it to span html element while sending to the cient(browser).

jQuery is a javascript library which works at client side.

And jQuery does not have any knowledge about ASP.Net or any server side technology, let alone server side control.Label jQuery ASP.Net

 

When you use asp:Label Control, span html element is generated

Server side:


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

Client Side:


<span id="lbl">Label</span>

 1. Set the value of Label control using jQuery

To set the value of Label control in client side, we can set the HTML content using jQuery. html() function is available for the same.

In the below code, we are getting the value from TextBox control and set that value to Label.


var txtValue = $('#<%=txtLabelText.ClientID%>').val();

$('#<%=lbl.ClientID%>').html(txtValue);

2. Get the value of Label control using jQuery:

If you use the same html() function without any parameter, it would get you the value of HTML content .


$('#<%=lbl.ClientID%>').html()

Complete Code:

Complete code of javascript and ASPX markup

Javascript:


<script type="text/javascript" src="jquery-1.11.2.min.js"></script>

<script type="text/javascript">

&nbsp;

function setLabelText(e) {

e.preventDefault();  // To prevent postback

var txtValue = $('#<%=txtLabelText.ClientID%>').val();

$('#<%=lbl.ClientID%>').html(txtValue);

}

function getLabelText(e) {

e.preventDefault(); // To prevent postback

alert($('#<%=lbl.ClientID%>').html());

}

&nbsp;

</script>

ASPX Markup:


<form id="form1" runat="server">

<div>

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

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

<asp:Button ID="btnSetLabel" runat="server" Text="Set Label Text" OnClientClick="return setLabelText(event);" />

<asp:Button ID="btnGetLabel" runat="server" Text="Get Label Text" OnClientClick="return getLabelText(event);" />

&nbsp;

</div>

</form>

Thanks for reading the article. If you like this article, please subscribe.

Want actionable useful articles on .Net development?