Search code examples
javascriptasp.nethtmlrunatserver

Javascript conflicts with Asp.net runat=server attribute


I am running some java script with a couple html controls. Everything works fine.

Except when I add the runat = " server" attribute to the html control, so I can access it in the code behind, the java script function does not work. Is this a common thing? Is there a work around for using a runat = " server" attribute with java script?

Or how can I access my Html control in the code behind WITHOUT using the run at server attribute?

Confused.


Solution

  • This is most likely occuring because your markup looks something like this:

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
        <div runat="server" id="myDiv">
        </div>
    </asp:Content>
    

    i.e. You're using a MasterPage or something else that acts as an INamingContainer. This results in the ID that's written out in the markup looking something like this:

    <div>
        <div id="ContentPlaceHolder1_myDiv">
        </div>
    </div>
    

    If you're using asp.net 4 you can change your markup for myDiv by adding clientidmode="Static" and you'll then get:

    <div>
        <div id="myDiv">
        </div>
    </div>
    

    Meaning your javascript will work again. If you're using earlier versions of asp.net then you'll need to do as SHAKKIR SHABBIR suggested and use <%=myDiv.ClientId%> to reference the element in your javascript so you get the "renamed" version of the ID that asp.net produces.