1

I have a piece of code in javascript which calculates something ,

There is a label in asp.net application , How can I get the value of it from javascript ?

here is i have tried :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<!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>JASP</title>
        <script type="text/javascript">
            var x = document.getElementById("Label1").innerHTML;
            alert(x);
        </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server" Text="My Text"></asp:Label>
    </form>
</body>
</html>
1
  • 1
    @Parkhid - You may have an issue with this code because you're trying to get a value out of your element before the DOM has finished loading. Commented Oct 20, 2011 at 15:46

3 Answers 3

1

Try this:

var data = document.getElementById('<%=Label1.ClientID%>').innerHTML;

Update:

Create a function, place your code inside that and call it where appropriate. Ex:

<script type="text/javascript">
    function displayText() {
        var x = document.getElementById('<%=Label1.ClientID%>').innerHTML;
        alert(x);
    }
</script>

Now call the function displayText(), where required.

Sign up to request clarification or add additional context in comments.

Comments

1

If you check your rendered source code you will see that the Label has been converted into a HTML span tag, and that the ID has also been re-rendered to ensure it is unique.

Therefore, you can use the ClientID property to find out what the rendered ID will be:

var x = document.getElementById('<%=Label1.ClientID%>').innerHTML;

Comments

0

You can get the value using the code below:

var value = document.getElementById('Label1').innerHTML

Note: You ideally just want the text and not the HTML, but if you have to support versions of Internet Explorer prior to 9, then you will need to use a combination of textContent and innerText.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.