Search code examples
javascriptjqueryformsform-submitonsubmit

On submit event get fired multiple times when there's multiple forms


I have multiple forms in a php page, I added forms in the parentForm array like this

 parentForm.push($('.js-address-form form'));

The issue is when i submit one form the onsubmit event get fired for all the forms existant in the page, so if i have 2 forms, the ajax request is called 2 times.

 jQuery.each(parentForm, function(i, val) {
            $(document).on('submit',val, function(event) {
               
                    $.ajax({
                        type: method,
                        url: lpd_front_controller,
                        async: false,
                        data: {
                            ajax: true,
                            action: 'Add',
                            id_customer: lpd_id_customer,
                            customer_token: lpd_customer_token,
                            id_guest: lpd_id_guest,
                            guest_token: lpd_guest_token,
                            consent_section: consent_section[i]
                        },
                        error: function(err) {
                            console.log(err);
                        }
                    });
               
            });
        });

I like when i submit a form the form onsubmit event will be fired one time


Solution

  • Your issue is that the .on jquery function does not accept a jquery object as the 2nd argument, only another selector:

    https://api.jquery.com/on/

    .on( events [, selector ] [, data ], handler )

    selector

    Type: String

    A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

    You can use the original selector in the event, eg:

    $(document).on('submit', '.js-address-form form', function(event) {
    

    or add the events directly within the loop - given how you're creating the loop based on existing items, you don't need event delegation, so:

    jQuery.each(parentForm, function(i, val) {
        $(val).on('submit', function(event) {