.Live (),. Delegate () or .on () do not work for dynamically loaded forms per page

I have an infinite scroll page. The ajax functionality is great for forms that exist on the page upon initial loading, but it doesn’t work for forms loaded using the ajax inifinite scroll function. I searched for about 5 days, trying to find the answer and am not yet. Here is the javascript part:

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

The reason for the :not(.member) is that other forms on the page, such as the search form, are not included in the script.

I tried

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

and

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

and

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

None of them work on forms loaded AFTER loading the start page. Anyone have any other suggestions? By the way, I am using jQuery 1.7.1. I also tried

 $("form:not(.member)").bind('submit', function() 
+4
source share
4 answers

Here you are misusing event delegation.

Forms are also loaded dynamically, so they are not included in $("form:not(.member)") , when the code runs, they do not exist yet.

Use delegation for the parent element that contains the forms :

 $('#formsContainer').on('submit', 'form:not(.member)', function() { ... }); 
+4
source

Your syntax is just wrong, that's it. These features 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 try to bind an element to be destroyed, your listener will also be lost.

Frankly, I do not think that the part of 'form:not(".member")' does not suit me either. Are you sure the correct syntax for not ? I just took your word here.

In any case, the best way: either #someListener is an ancestor that has no other forms (for example, a search form), or you give this particular kind of form to a class. Thus, instead of excluding .member forms, you should TARGET only this form:

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

Or, if the Ajax content block (form and all) has some kind of shell, you can add a class to it (say, ".ajaxBlock" ) and do it like this:

 $('#someLIstener').on('submit', '.ajaxBlock form', function() { ... }); 
+2
source

None of the above answers worked. The solution assigned onclick = "function" to all comment forms, including those already loaded.

+2
source
 $("#parentContainer").on("submit", "form:not(.member)", function() { // code }); 
0
source

Source: https://habr.com/ru/post/1392344/


All Articles