1

How can I access the value of an ASP.NET Literal control from JS. I have the below but it doesn't work:

var companyname = document.getElementById('litCompanyName').text;
var companynumber = document.getElementById('litCompanyNumber').text;

Thanks

2
  • Check it here! Commented Sep 18, 2014 at 12:26
  • Can you show your asp:literal syntax? Commented Sep 18, 2014 at 12:29

4 Answers 4

1

You must public your literal in a webform/view, because you can't public asp.net code in .js files, you can do something like this:

<script>
var litCompanyName = <%= [YOUR LITERAL]; %>
</script>

and then use it

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

Comments

1

In Asp.net When Page is Going to Rendered it will change its ID in Html. Check Html of Page using FireBug in Mozilla Firefox.

example of label

<asp:Label ID="SaveTime" runat="server"></asp:Label>

  var companynumber=  document.getElementById('<%=SaveTime.ClientID%>').Text

and For Literal You Need to Wrap with div or span

<span id="yourId"><asp:Literal  ID="SaveTime" runat="server"></asp:Literal></span>

js:

var value= document.getElementById('yourId').innerText;

Comments

0

The short answer is that you can't. A literal control is just that. The value in the Text property is 'literally' outputted to the response stream.

You can either set a hidden field or use a Label. Just remember, referencing ASP.NET controls from Javascript, it's easier to use ClientIDMode="Static" or wrap your literal in a span with an ID.

For example:

litCompanyName.Text = "<span id=\"company-name\"> + Company.Name + </span>";

Then in your JS

var companyname = document.getElementById('company-name').text;

Comments

0

The literal control only exists on the server side, when the page is rendered it's only the text of the control that ends up in the page. So if you have:

The company name is <asp:Literal ID="litCompanyName" runat="server" Text="Google" />

all that ends up in the HTML code is:

The company name is Google

To access the text from Javascript you need an element around the text, for example:

<span id="CompanyName"><asp:Literal ID="litCompanyName" runat="server" /></span>

Now you can use document.getElementById('CompanyName').innerHTML to get the text from the literal.

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.