1

I have a page that has similar events going on but halfway through it loads new content and a lot of the jQuery doesn't work when the new content loads.

It's basically a 'game' where you answer a bunch of question (handled through AJAX) and when all of the content on the first 'level' is answered, it takes you to the next level. Once all the questions are answered, I 'empty()' the main content div and then use this:

$('#content').load('next_page.php', function(){
$.getScript("js/new_functions.js",function(){           
        $('form.sample_form').on('submit', function(e){                                 
            e.preventDefault();
            alert('test');
        });
    });
});

It loads the information in and does a couple PHP calls to a database to populate the content in the forms. I then want there to be a submit function on the forms after they load. I originally had the 'submit' function in the 'new_functions.js' page but it didn't work that way. I'm assuming this is because there is an AJAX function in the new_functions.js file and that this runs asynchronously so the forms aren't set up before the form.sample_form submit function gets applied (even though it's only applied after the new_functions.js file is loaded). If I run the submit function within the AJAX function, there's a variety of problems so that didn't work.

So my question is how I'm able to apply submit functions to the forms only after the new page is loaded, the new functions file is loaded and all of the AJAX is run.

MillerMedia
  • 3,651
  • 17
  • 71
  • 150
  • 1
    Your easiest solution is probably to switch to delegated event handling for any form events. You can read about how to implement that different form of `.on()` [here](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376) and [here](http://stackoverflow.com/questions/9985090/jquery-on-does-not-work-but-live-does/9985137#9985137) and [here](http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409) in previous answers on this topic. – jfriend00 Mar 27 '14 at 03:30

1 Answers1

1

What works for me is to set all the following inside a $(document).ready

$(document).on('submit','form.firstForm', function(event){
    event.preventDefault();

    handleData();
});

 $(document).on('submit','form.secondForm', function(event){
       event.preventDefault();
       handleData();
});

Also if you have plugins for inputs that you reuse in each form, wrap them like this so that after each ajax operation they are initialized

$(document).ajaxComplete(function(event, xhr, settings) {
        $("#inputdate").pickadate();  

        $("#inputtime").pickatime();
});
Miguel_Velazkez
  • 180
  • 2
  • 12