2

Currently, I wrote Ajax Form that works very well, all output from the form will puts in Result, expect when the result of form is another form at this time, my script doesn't works for new form that was the result of old form

My script doesn't work for new form So, I needs to make that new form works like old one, is that possible ?

$(document).ready(function()
{
    $("form").submit(function(e)
    {
        e.preventDefault();
        $("#Result").html("<div id='Loading'></div>");

        $.ajax(
        {
            type: "POST",
            data: $(this).serializeArray(),
            success: function(Data)
            {
               $("#Result").html(Data);
            }
        });
    });
});
Patton Pierce
  • 317
  • 1
  • 2
  • 14
  • 1
    Are you saying that the response from the ajax call could be another form, which is then not behaving in the same way as the first form? – Pabs123 Jan 26 '16 at 00:28
  • @Pabs123, yes exactly – Kamran Borbor Jan 26 '16 at 00:29
  • @Kamran Borbor share the HTMl code as well. Verify the structure how new form is being populated. – pratikpawar Jan 26 '16 at 00:31
  • 1
    @juporag `.live()` has been obsolete for some time, you should link to an example that uses `.on()` instead. – jmoerdyk Jan 26 '16 at 00:35
  • Form submit event for form as new element is not working because it is dynamic element in this case. Check out the similar issues and problems on SO. Also juporag 's reference is what you are looking for. add an event listener on parent element of form. `body / document` – pratikpawar Jan 26 '16 at 00:38
  • @pratikwebdev, the example of my script http://paste.ubuntu.com/14667980/ – Kamran Borbor Jan 26 '16 at 00:42

2 Answers2

2

Try

$("#Result").on("submit", "form", function(e) { 
    ...  YOUR CODE  .....
});

EDIT: If you want to catch a global form submit event (Thanks @pratikwebdev):

$(document).on("submit", "form", function(e) { 
    ...  YOUR CODE  .....
});
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
1

Try this:

$("body").on("submit", "form", function(e){ 
  //Your code.
});

The problem you were having, happened because when you added the submit listener to "form", the dynamically created form elements didn't exist, so those new form didn't had a listener attached to them.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

More info on jQuery.on and event delegation

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98