jQuery's .on() method combined with the submit event

JqueryAjaxFormsSubmit

Jquery Problem Overview


I've got a problem with .on(). I have multiple form-elements (forms with class="remember"), also I add another one form.remember using AJAX. So, I want it to handle submit event something like:

$('form.remember').on('submit',function(){...}) 

but form added with AJAX doesn't work with it.

Where is the problem? Is it a bug?

Jquery Solutions


Solution 1 - Jquery

You need to delegate event to the document level

$(document).on('submit','form.remember',function(){
   // code
});

$('form.remember').on('submit' work same as $('form.remember').submit( but when you use $(document).on('submit','form.remember' then it will also work for the DOM added later.

Solution 2 - Jquery

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

Solution 3 - Jquery

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnton AbramovView Question on Stackoverflow
Solution 1 - JqueryDipesh ParmarView Answer on Stackoverflow
Solution 2 - Jqueryvitor_gaudencio_oliveiraView Answer on Stackoverflow
Solution 3 - JqueryDanialView Answer on Stackoverflow