Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Script Doesn't work for new elements [duplicate]

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);
            }
        });
    });
});
like image 565
Kamran Borbor Avatar asked Apr 10 '26 10:04

Kamran Borbor


2 Answers

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  .....
});
like image 136
Alon Eitan Avatar answered Apr 11 '26 22:04

Alon Eitan


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

like image 25
Marcos Casagrande Avatar answered Apr 12 '26 00:04

Marcos Casagrande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!