JavaScript code works if embedded in aspx page, but not if included in .js file

Say if you are using the following JavaScript function to alert user if a TextBox is empty:

<script language="JavaScript" type="text/javascript">
    function validateInput()
        if (document.getElementById('<%=TextBox1.ClientID%>').value="")
            alert("The text box is empty!");

If the above code is embedded in the aspx page, it works as expected. But if you put the above function in a .js file and include it in your aspx file, you will get a “Object expected” error in IE, or “document.getElementById(‘<%=TextBox1.ClientID%>’) is null” error in FireFox. What is the problem?

The reason is if the code is embedded in aspx page, when ASP.NET renders the aspx page, it will execute <%=TextBox1.ClientID%> to get the actural ID of the TextBox. If you view the page source after the page is loaded, you will find document.getElementById(‘<%=TextBox1.ClientID%>’) becomes document.getElementById(‘TextBox1’), so it runs fine. However, if the code is included in a .js file, ASP.NET will not execute <%=TextBox1.ClientID%>, so the JavaScript will literally try to find an element with ID=<%=TextBox1.ClientID%> , of course it can’t find it, then it gives the above error. You will need to change document.getElementById(‘<%=TextBox1.ClientID%>’) in the .js file to document.getElementById(‘TextBox1’), to make it work .

So the bottom line: if you want to use .js file in aspx page, make sure you don’t have any server-side code in it, because ASP.NET will not execute them.

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Mike Recent comment authors
newest oldest most voted
Notify of

Thanks man! Helped me alot!!!