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?
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?
Share Improve this question edited Nov 5, 2013 at 0:01 user457812 asked Nov 4, 2013 at 23:36 Amie CrutchleyAmie Crutchley 1211 gold badge2 silver badges12 bronze badges 2- what do you mean by "doing form submit function"? – Michał Rybak Commented Nov 4, 2013 at 23:50
- $("#processor1").on( "submit", function( event ) { – Amie Crutchley Commented Nov 4, 2013 at 23:52
2 Answers
Reset to default 2If 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
...
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.