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>
No solution here worked for me. Instead I added a class to the label and was able to select it that way.
<asp:Label ID="Label1" CssClass="myLabel1Class" runat="server" Text="Label"></asp:Label>
$(".myLabel1Class").val()
And, as mentioned by others, make sure you have your jquery loaded.
Try:
try document.getElementById('<%=Label1.ClientID%>').text or innerHTML OTHERWISE LOAD JQUERY SCRIPT AND put your code as it is....
for the line you wrote
you missed adding #. it should be like this
also I do not prefer using this method
that's because if you are calling a control in master or nested master page or if you are calling a control in page from master. Also controls in Repeater. regardless the MVC. this will cause problems.
you should ALWAYS call the ID of the control directly. like this
this is simple and clear. but do not forget to set
in your controls to remain with same ID name after render. that's because ASP.net will modify the ID name in HTML rendered file in some contexts i.e. the page is for Master page the control name will be ConetentPlaceholderName_controlID
I hope it clears the question Good Luck
Try this
It's simple, set a specific value for that label (XXXXXXX for example) and run it, open html source of output (in browser) and look for XXXXXXX, you will see something like this
<span id="mylabel">XXXXXX</span>
it's what you want, the ID of<span>
(I think it's usually same as Label name in asp code) now you can get its value by innerHTML or another method in JQuery