Devon Bessemer
Devon Bessemer

Reputation: 35337

Where is the correct place to load a javascript function so it is applicable for ajax loaded pages?

Right now I have a:

$(window).load(function(){
  $('form').submit(function() {
  ...
  });
});

But this only works for the parent page. If I load a document with .load() or .ajax() the submit() function for the form is not applicable. So I take it I'm not supposed to use .load() or I'm not supposed to use it on window. Where is the correct location if I want the .submit() it to work for ajax loaded documents?

Solution:

 $(document).ready(function(){
   $(document).on('submit', 'form', function() {
      ...
   });
 });

In solution: this still references the form as noted by Jquery documentation.

Note for anyone else who may run into an issue with .toLowerCase() or .toUpperCase(), these functions will break your script if the string is empty.

Upvotes: 0

Views: 41

Answers (1)

adeneo
adeneo

Reputation: 318202

It doesn't have anything to do with the window.onload, but you should generally use document.ready with jQuery.

It has something to do with the fact that event handlers are only bound to the elements that match the selector at the time of binding, and $('form') only matches the forms on the page now, not any forms you might add later.

The solution is to delegate the event to an element that exists now, and filter for target elements, and you'd do that like so :

$(document).ready(function(){
    $(document).on('submit', 'form', function() {
       ...
    });
)};

Upvotes: 3

Related Questions