Tutorial :Jquery user control



Question:

I have a problem with jquery not loaded in an asp user control.

I want simply to add the click event when a checkbox is clicked.

Here is my javascript file

$(document).ready(function() {      var arr = jQuery(":checkbox[id*='drpAccountType']");      for (i = 0; i < arr.length; i += 1) {          $("#" + arr[i].id).click(function() { alert(this.id) });      }  });  if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();  

The user control pre render events:

Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender          ScriptManager.RegisterClientScriptInclude(Me, Me.GetType, "CheckboxdropdownScript", ResolveUrl("~/Scripts/CheckBoxDropDown.js"))  End Sub  

the script is loaded fine but any usage of jQuery return undefined. Then only when the page is loaded I can excute the same code for the commande line in firebug. The jquery library is loaded in the master page.

Whenever I'm using jquery within an asp user control I always find problems, and I always have to hack around to get it to work. I try all the entries in stackoverflow but I never found a one as general solution.

did any one found a simple solution to use jquery with master pages, user control in asp.net I would appreciate if someone can share such valuable information.

My manager is about to drop jquery from the application as we always waist lot of time just to find a workaround to have it to work with user controls.

Please help, I like jquery and I really want to use it for client script.

best regards


Solution:1

your script may be getting inserted into the page before the jquery library. (You can verify this by checking the HTML output of your page.)

When script files execute JS inline, and especially when that JS depends on other libraries, it's safest to use RegisterStartupScript rather than RegisterClientScriptInclude. If you use this overload of RegisterStartupScript, you can construct a reference to the same external JS file and it'll run in the right place.

As an alternative, you could use <asp:ScriptReference/> tags in a ScriptManagerProxy in your user control rather than registering the script in Page_Load or Page_Init; in my experience, those scripts are added after scripts from the master page.


Solution:2

this is not exactly a direct answer but here are some jQuery ASP.net controls that might help:

http://clipperhouse.com/jQuery/

(Look for the bit about Callbacks.)

Also, you might not need the "for" loop if you simply give all your checkboxes a class name and use that as the selector.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »