Martin Currah
Martin Currah

Reputation: 517

Detect a form submit in jQuery when it has been dynamically added to the DOM

Scenario:

I have a select box with it's data populated by data from a php config file. If there isn't a matching value in the select to choose from, I am allowing the user to add a field to it. I have created a small one input form which is added via jQuery and I want to catch the post submission to then defer it to an ajax function.

Problem:

As the form is dynamically added I am unable to catch the form submission and the page ends up reloading.

This doesn't work:

$('form[name="add"]').on('submit', function(e) {.....

One solution:

If I don't use a form element and simulate it in a div I can get around by using

$(document).on('click', 'div.add_form a[name="submit"]', function() {.....

However:

Although the solution above works I would appreciate if 1) someone could educate me if it is possible to catch a submission from a form that has been dynamically added to the page using jQuery, and 2) if it would be 'good practice' to use that method

Update

$(document).on('submit', 'form[name="add"]', function(e){ 
    console.log('here')
    e.preventDefault() 
})

This event delegation is NOT catching the form as I can see from the console with preserve log enabled

Upvotes: 2

Views: 2055

Answers (1)

rrk
rrk

Reputation: 15846

Binding dynamically added elements to events can be done using the following. See what Event Delegation is.

$(document).on('click', 'div.add_form a[name="submit"]', function(){
    //your code
})

Same principle applies to dynamically added forms. Change the event to submit and use a selector which will be valid for the dynamically added forms too.

$(document).on('submit', '[selector-for-your-form]', function(){
    //your code
})

Upvotes: 7

Related Questions