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

微笑、不失礼 提交于 2019-12-04 09:31:18

问题


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

whenever i try to manipulate an asp element using javascript i get a "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


回答1:


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 %>');



回答2:


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%>');



回答3:


If you have a textbox:

<asp:TextBox id="txtText" runat="server" />

YOu can use:

var textBox=document.getElementById('<%=txtText.ClientID %>');

Any WebControl exposes the same ClientID property.




回答4:


All though the question has been answered, thought I would just post some further info...

Rick Strahl provided quite an intresting work around to this problem.

http://www.west-wind.com/WebLog/posts/252178.aspx

Thankfully when ASP .NET 4.0 arrives, it will allow you to specify exacly what the client ID's will be!

http://www.codeproject.com/KB/aspnet/ASP_NET4_0ClientIDFeature.aspx



来源:https://stackoverflow.com/questions/675060/how-can-i-access-runat-server-asp-element-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!