I have 2 textboxes that I’m trying to capture the onchange event for. These textboxes are within a user control that is within an asp.net updatepanel. Every time I change the textbox text, I receive a “Microsoft JScript runtime error: Object expected” error that doesn’t provide any other helpful information.
Here is the code:
<script type="text/javascript">
function ResetOrientationImage() {
var width = (+document.getElementById('<%= txtWidth.ClientID %>').value);
var height = (+document.getElementById('<%= txtHeight.ClientID %>').value);
if (width > height) {
document.getElementById('<%= imgOrientation.ClientID %>').src = "images/buttons/Landscape.png";
} else {
document.getElementById('<%= imgOrientation.ClientID %>').src = "images/buttons/Portrait.png";
}
}
</script>
<asp:TextBox ID="txtWidth" runat="server" Width="50px" onchange="ResetOrientationImage()" Text="0"></asp:TextBox>
<asp:TextBox ID="txtHeight" runat="server" Width="50px" onchange="ResetOrientationImage()" Text="0"></asp:TextBox>
<asp:Image ID="imgOrientation" ImageUrl="~/images/buttons/Portrait.png" runat="server" />
I thought it must be a problem with the javascript, but I put this exact code into a standalone .aspx page and it executes correctly with no errors.
EDIT
Upon looking in Firebug, the real error is that the ResetOrientationImage function cannot be found when the page executes. If I move the javascript out of the user control onto the page itself, it works as I would expect. Why can’t the javascript live in the user control?
I stumbled upon this question which gave me my answer:
Javascript object "is not defined" error after ScriptManager.RegisterClientScriptInclude
I moved my javascript function into an external file and referenced it in the user control code behind like this: