Neither .live(), .delegate() or .on() work for forms loaded dynamically to the page

2k views Asked by At

I have a page with infinite scroll. The ajax functionality works fine for forms existing on the page when it initially loads, but doesn't work for forms loaded from the inifinite scroll ajax feature. I've searched for about 5 days trying to find a answer and haven't yet. Here is a portion of the javascript:

$("form:not(.member)").submit(function() {
     var status_id = $('#status_id').val(), 
    etc..........

The reason for the :not(.member) part is so the other forms on the page, such as the search form, aren't included in the script.

I've tried

 $("form:not(.member)").live('submit', function() {

and

 $("form:not(.member)").on('submit', function() {

as well as

 $('body').delegate('submit', 'form:not(.member)', function() {

None of these are working on the forms loaded AFTER the initial page load. Does anyone have any other suggestions? I'm using jquery 1.7.1 by the way. I've also tried

$("form:not(.member)").bind('submit', function()
4

There are 4 answers

2
Greg Pettit On

Your syntax is just wrong, that's all. Those functions should work. Using .on() as an example:

$('#someListener').on('submit', 'form:not(.member)', function() { ... });

Where someListener is an ancestor element that is NEVER destroyed by the AJAX function. If you're trying to bind to an element that gets destroyed, your listener gets lost as well.

Have to admit, I don't think the 'form:not(".member")' part doesn't look right to me, either. Are you sure that's the correct syntax for not? I'm just taking your word for it here.

There's a better way anyhow: either #someListener is an ancestor that does not have your other forms within (like the search form), or you give this specific kind of form a class. So instead of excluding .member forms, you would TARGET just this kind of form:

$('#someListener').on('submit', '.dynamicForm', function() { ... });

Or, if the Ajax content block (form and all) has a wrapper of some sort, you could add a class to it (say, ".ajaxBlock") and do it this way instead:

$('#someLIstener').on('submit', '.ajaxBlock form', function() { ... });
0
Didier Ghys On

You are using the event delegation wrong here.

The forms are also loaded dynamically, so they are not included in $("form:not(.member)") when the code runs, they don't exist yet.

Use delegation on a parent element that contains the forms:

$('#formsContainer').on('submit', 'form:not(.member)', function() {
     ...
});
0
The Alpha On
$("#parentContainer").on("submit", "form:not(.member)", function() { // code });
0
Mike On

None of the above answers worked. The solution was assigning onclick="function" to all of the commenting forms including the ones already loaded.