Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById not finding control generated by ASP.net

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??

like image 988
Johnrad Avatar asked Jan 04 '11 16:01

Johnrad


3 Answers

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";
    }
}
like image 159
hunter Avatar answered Oct 20 '22 09:10

hunter


"hunter" gives a pretty solid way of doing things, however a, in my opinion far better method is to use the "CliendIDMode" property on the control and set that property to "Static". This will make the client and server IDs the same. Like this:

<asp:TextBox ID="ServerAndClientId" runat="server" ClientIDMode="Static" />
like image 30
Maverick Avatar answered Oct 20 '22 08:10

Maverick


The ID of the label is not "lblError". The ASP.net engine changed the ID. Check the HTML source code in the browser to find out the real ID.

like image 41
Šime Vidas Avatar answered Oct 20 '22 07:10

Šime Vidas