getElementById not finding control generated by ASP.net

Johnrad picture Johnrad · Jan 4, 2011 · Viewed 68.1k times · Source

I am simply trying to store a label in a variable in javascript but for some reason this isn't working with document.getElementById('control');. I know my javascript is linking to my html file fine because everything else works.

Here is my javascript code:

function performEvapCooledCircuit(txt)
{
    var error = document.getElementById('lblError');


    if (txt.value == null || isNaN(txt.value))
    {
       error.style.visibility = "visible";
    }
}

Here is the html code for my label:

<asp:Label ID="lblError" class="NormLabel" runat="server" 
   style="color:red; visibility:hidden;" Text="Invalid Input."></asp:Label>

I am getting an error that says object expected??

Answer

hunter picture hunter · Jan 4, 2011

The ID that ASP.NET will generate will not be "lblError" so you'll need to reference it by its ClientID

document.getElementById('<%=lblError.ClientID %>');

If your javascript file is external I've usually had to write a type of "Init" javascript method to make sure my ID's were set up property

On your ASPX page:

<script type="text/javascript">
    var lblError = null;
    function InitializeVariables()
    {
        if (lblError == null) // make sure you only do this once
        {
            lblError = document.getElementById("<%=lblError.ClientID %>");
        }
    }
</script>
<asp:Label 
    ID="lblError"
    class="NormLabel"
    runat="server" 
    style="color:red; visibility:hidden;"
    Text="Invalid Input."></asp:Label>

Then in your javascript file you'll have to call InitializeVariables() to make sure you've got the variables pointing to the proper asp.net controls

function performEvapCooledCircuit(txt)
{
    InitializeVariables();

    if (txt.value == null || isNaN(txt.value))
    {
        lblError.style.visibility = "visible";
    }
}