Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text of label with jquery

I want to do very simple thing, but I'm not success. I have button and label on my asp.net page and I want to get text of label after clicking on button. Here is my code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="DynamicWebApplication.WebForm2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml">  <head runat="server">     <title></title>         <script type="text/javascript">         function f()          {             var g = $('<%=Label1.ClientID%>').val();  // Also I tried .text() and .html()             alert(g);         }     </script> </head>  <body>     <form id="form1" runat="server">         <div>             <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>             <p></p>             <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="f();"/>         </div>     </form> </body> 

like image 759
Rougher Avatar asked Aug 07 '11 12:08

Rougher


People also ask

How do I get text from labels?

Use the textContent property to get the text of a label element, e.g. const text = label. textContent . The textContent property will return the text content of the label and its descendants. If the element is empty, an empty string is returned.

Can HTML label have a value?

The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to.


1 Answers

try this:

var g = $('#<%=Label1.ClientID%>').val(); 

or this:

var g = $('#<%=Label1.ClientID%>').html(); 

you are missing the #

add this in the head section:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
like image 76
kleinohad Avatar answered Sep 18 '22 10:09

kleinohad