Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...