Amie Crutchley
Amie Crutchley

Reputation: 121

Dynamic JQuery Form Submit for Multiple Forms

I have PHP that searches a database and then echoes an html form for each result found. These are loaded via AJAX into the main HTML page into a div on document load.

Now I want to have listeners for each of these forms submitting. They all have the same inputs. Each form has an incremental ID of processor (processor1, processor2, processor3, and so on).

So, depending on the results, it could be as little as one form or 50 forms. Is there a dynamic way of doing a form submit function rather than writing countless repetitive functions?

Upvotes: 2

Views: 10624

Answers (2)

Michał Rybak
Michał Rybak

Reputation: 8706

If using classes is (for some reason) not an option, you can also use 'starts with' selector:

$('#processor*').submit(function (e) { 
    e.preventDefault(); 
    ...
});

Note that the above function should be called as a callback to AJAX function that loads the forms.

Upvotes: 0

DarthTux
DarthTux

Reputation: 156

If you have

<form id="form1">
<form id="form2">

You can use a class selector

<form id="form1" class="forms">
<form id="form2" class="forms">

In jQuery:

$(function() {
 $('.forms').submit(function(e){
   e.preventDefault(); //Prevent submit
   console.log($(this)); //Current form submiting

   //Make ajax call for current form
 })
})

If u you need extra data for each form, you can use data atributte

<form id="form2" class="forms" data-myattr="myvalue">

And get it

...
$(this).data('myattr'); //myvalue
...

Upvotes: 2

Related Questions