views:

29

answers:

2

Hi, I'm using $('#container').load method to handle loading all the subpages of my site. Now the deal is, some sub-pages require extra behavior (like form validation etc.)

I'd love them to be self-contained, so - each sub-page has own JS code that handles all the subpage-specific tasks. This however requires some of them to handle "loaded" callback to access the just-loaded DOM nodes.

Any tips on how to achieve it? I tried putting Copy code

<form id="my-form"> .. </form>
<script>
$('#my-form').ready(function() {
    //..
});</script>

but it doesn't seem to be triggered when loaded via AJAX.

A: 

Since your form/page is loaded, you need to use either of live or delegate method, for example here is how you could validate your form:

$('#my-form').live('submit', function(){
  // your validation code....
});

The live or delegate methods work on any element present now or in future.

More Info:

Sarfraz
In jQuery versions lower than 1.4, non-bubbling DOM events like *submit*, *focus* and *blur* cannot be used with *live()*. As long as you stick to the newer versions, this won't be a problem.
Andy E
@Andy E: Yes agreed, we assume latest version of jquery is used, after all it has various fixes especially with event handling.
Sarfraz
the code you provided needs to be put in the "main" code, not the loaded subpage.
migajek
A: 

Finally I've figured out the problem. It was all about content filtering (second parameter of .load method). Now, instead of filtering on JS side, I'm doing it server-side.

migajek