How to iterate each form of same class and handle submits uniquely with jQuery?

1.5k views Asked by At

I have multiple forms on the same page with the class form_delete.

How do I iterate over those forms in jQuery adding a submit event that will uniquely apply to each form?

I've tried this using $('.form_delete').each(...); but when I add $(this).submit(...) events it's not working (event does not register).

Forms:

<form class="form_delete">
</form>

<form class="form_delete">
</form>

<form class="form_delete">keep adding n forms to infinity ;)

jQuery:

$('.form_delete').each(function() {
    $(this).submit( function(event) { 
        // Nothing gets registered here
    });
}
3

There are 3 answers

0
chris97ong On BEST ANSWER
$('.form_delete').each(function() {
    $(this).on("submit", function(e) { // submit button pressed
        // prevent form from doing what it normally does when submit button is pressed
        e.preventDefault();

        // do anything else that you want to do when the submit button is pressed
        alert( "Hi");

    });
});
0
Mohamed-Yousef On

I don't know why you use .each(); anyway if all forms with same class just use

$('.form_delete').on('submit',function(e){
    e.preventDefault();
    alert($(this).index());
    return false;
});

in that case you will need something like data-selectForm to define which form you submited

<form class="form_delete" data-selectForm="firstform">
</form>

<form class="form_delete" data-selectForm="secondform">
</form>

and then use

$('.form_delete').on('submit',function(e){
        e.preventDefault();
        alert($(this).data('selectForm'));
        return false;
    });
1
Nathanael Smith On

jQuery's event delegation is also an option.

    $('body').on('submit', '.form_delete', function submitCB(e) {
       e.preventDefault();  
    });

When the event bubbles up to the body then jQuery will check the target element against the string selector (parm 2), and only call the callback (parm3) if it matches.

This way you only have on event listener on the page, as opposed to many.