Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access runat="server" ASP element using javascript?

It seems everyone is doing this (in code posts etc.)...but I don't know how. :(

Whenever I try to manipulate an asp element using JavaScript I get an "element is null" or "document is undefined" etc. error.....

JavaScript works fine usually,...but only when I add the runat="server" attribute does the element seem invisible to my JavaScript.

Any suggestions would be appreciated.

Thanks, Andrew

like image 810
Andrew Avatar asked Mar 23 '09 20:03

Andrew


People also ask

Can you use ASP.NET with JavaScript?

ASP.NET requires the use of the client-side Javascript, as that's how ASP.NET handles its Events via PostBacks.

How do I use a Runat server?

To make these elements programmable, add a runat="server" attribute to the HTML element. This attribute indicates that the element should be treated as a server control. The id attribute is added to identify the server control. The id reference can be used to manipulate the server control at run time.


2 Answers

What's probably happening is that your element/control is within one or more ASP.NET controls which act as naming containers (Master page, ITemplate, Wizard, etc), and that's causing its ID to change.

You can use "view source" in your browser to confirm that's what's happening in the rendered HTML.

If your JavaScript is in the ASPX page, the easiest way to temporarily work around that is to use the element's ClientID property. For example, if you had a control named TextBox1 that you wanted to reference via JS:

var textbox = document.getElementById('<%= TextBox1.ClientID %>');
like image 67
Dave Ward Avatar answered Sep 28 '22 09:09

Dave Ward


Making an element runat="server" changes the client-side ID of that element based on what ASP.NET naming containers it's inside of. So if you're using document.getElementById to manipulate the element, you'll need to pass it the new ID generated by .NET. Look into the ClientId property to get that generated ID...you can use it inline in your Javascript like so:

var element = document.getElementById('<%=myControl.ClientID%>');
like image 25
Matt Winckler Avatar answered Sep 28 '22 09:09

Matt Winckler