Textbox not working when adding runat="server" RRS feed

  • Question

  • User-542418535 posted

    I am using Microsoft Visual Web developer 2010. I have Google Maps embedded on my webpage and a textbox (txtBoxInput) using the code:

    <input runat="server" type="text" id="txtBoxInput"/>

    A button which displays a new map loction:

    <input type="button" id="btnDisplay" value="Display map" style="height:34px;width:90px;" onclick="showPoint();"/>

    I also have an aspn.net button (btnTest) using the code:

    <asp:Button ID="btnTest" runat="server" onclick="Button1_Click" Text="Button"/>

    And the code in btnTest's event:

    protected void Button1_Click(object sender, EventArgs e)
    string test = txtBoxInput.Value = "New York, United States";

    When I click the button (btnTest), the textbox (txtBoxInput) gets filled with "New York, United States". I then click btnDisplay but nothing happens.

    When I remove runat="server" so that the code is:

    <input type="text" id="txtBoxInput"/>

    It works. When runat="server" is removed, txtBoxInput isnt recognised in the asp.net btnTest event.

    Is there a way to fix this? The cause must be because of the line:

     <input runat="server" type="text" id="txtBoxInput"/>
    Thursday, August 29, 2013 2:38 PM


  • User653228039 posted

    I'm going to make a guess, since I don't really know what showPoint does.

    I'm assuming showPoint grabs your textbox somehow, probably like so:


    var txtBoxInput = document.getElementById("txtBoxInput");
    //or with jQuery
    var txtBoxInput = $("#txtBoxInput");

    when you add runat="server", often times, ASP.NET prefixes that element's id with a string (something like "ctl001_") to protect the developer from themselves from accidentally giving more than one html dom element the same ID.

    ClientIDMode was a property added to System.Web.UI.Control so that you can override this default behavior.  


    So if you have a textbox like so:

    <asp:TextBox id="txtBoxInput" runat="server" ClientIDMode="Static"></asp:TextBox>

    then it is guaranteed to have the same ID on the client, helping your javascript references.  I'm not sure if this property is available on inputs with runat="server".

    Another, older technique that you could do (if your showPanel function is defined on the actual aspx page) is this:

    function showPanel()
       var txtBoxInput = document.getElementById('<%=txtBoxInput.ClientID%>');
       //keep going...

    this is because <%= is equivalent to "Response.Write()" so your server code executes first, applies the actual client ID in between the <%=%> and your javascript will see the actual id.  Again, this only works if the javascript is implemented on your aspx page (not in an external js file).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 29, 2013 2:53 PM