JTunney
JTunney

Reputation: 904

In ASP.NET Webforms how to run JavaScript when adding a UserControl to a page

I have a UserControl with many fields on it. In the ascx I have a document.ready() function where I hide some of the fields with JQuery. On a regular page when the page is loaded the fields are hidden and the JavaScript works.

Lets say when the user clicks a button and I dynamically add the UserControl to the page. The UserControl adds fine, but the JavaScript does not run to hide all of the fields within it that are initially supposed to be hidden.

At first I thought it was because it wouldn't work with document.ready since my actual page is already loaded. But then I realized the document.ready isn't running. So then I just wrapped all of my hide field lines in a function called initializeControls(); and tried calling it in the PageLoad event of the UserControl. I guess the controls are not fully loaded on the page at this point because I get a bunch of undefined errors.

Any ideas?

Upvotes: 0

Views: 1064

Answers (2)

JTunney
JTunney

Reputation: 904

This one was my fault. It actually was going into the document.ready when the control was dynamically added onpostback. The problem was that within UserControls I forgot everything is automatically given a different ID and I was hiding a div in jquery. Instead I made the div a panel and hid that based on ClientID.

Upvotes: 0

Maddy
Maddy

Reputation: 927

Add below code to end of your click event code in c#. Once your ASP.Net Server Processing Completes and page is loaded, it will call your javascript function.

ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "Script", "functionName();", True)

Otherthing, you can do initially hide your fields and use javascript to show those fields.

Upvotes: 1

Related Questions