Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 503
Mike Avatar asked Feb 22 '23 18:02

Mike


1 Answers

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() {
     ...
});
like image 152
Didier Ghys Avatar answered Apr 27 '23 03:04

Didier Ghys