开发者

jquery selector won't work on controls loaded with asp:UpdatePanel

I have a legacy code that uses asp.net updatepanel to load some pagination items. basically it will have some text boxes and some text. i need to check whether any checkbox is selected on click of a button. The jquery code that i have works for the initial load but when the aja开发者_JAVA技巧x load happens, the items loaded are no longer in the initial DOM so will not be considered for any jquery activities. we can use live or deligate for events but if i have to uses the control as a selector that won't help.

The code to check whether the checkbox is selected is strait forward but my concern is how do i rebind it after ajax call?

if ($('input:checked').length > 0) {
       alert('checked');
   }
   else {
          alert("not selected");
   }

Any ideas??


If you change the initial bind (or click or whatever, click is just a wrapper for bind) to either live or (better) delegate, they will survive updates to the underlying DOM elements.

Sadly the api.jquery.com site is having issues today, so those links won't be hyper-useful right now. Basically, though, if you have:

$("some_selector").click(function() { ... });

You can change it to

$("some_selector").live("click", function() { ... });

or (better)

$("some_parent_element_selector").delegate("selector_for_descendants", "click", function() { ... });

What happens there is that jQuery watches for the event on the parent element (or "body" in the case of live) and then checks to see whether the originating element matches the selector you gave. If so, it calls your handler as though it had been hooked on the actual element. Since the handler is on an ancestor element, not the actual descendant element, you can swap those out at will. This is sometimes called "event delegation" (hence the function delegate).

Example:

HTML:

<div id='container'>
  This is the container.
  <div class='foo'>
    This is the descendant of the container. Click me.
  </div>
</div>

JavaScript:

$("#container").delegate(".foo", "click", function() {
  $("<p>Element with class 'foo' clicked!</p>").appendTo(document.body);
});

Live copy


jQuery $(document).ready and UpdatePanels?


There is a solution on codeplex: http://updatepanelplugin.codeplex.com/discussions/70810

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜