You can listen to the clicks of the element button
in specific and within it determine by $(this).closest('form');
to which form the button that was pressed is linked.
That way you will work with that single form.
Example with three forms ... but they can be 10, or more, or less.
$(function() {
$('button').on('click', function(e) {
e.preventDefault();
var frm = $(this).closest('form');
var data = frm.serialize(); //Almacenamos los elementos del form
console.log(data);
alert('Enviaste el formulario con id: '+frm.prop('id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frm1">
Escriba datos: <input type="text" name="inputTest" placeholder="Escribe algo en frm1" />
<button>Enviar frm1</button>
</form>
<hr />
<form id="frm2">
Escriba datos: <input type="text" name="inputTest" placeholder="Escribe algo en frm2" />
<button>Enviar frm2</button>
</form>
<hr />
<form id="frm3">
Escriba datos: <input type="text" name="inputTest" placeholder="Escribe algo en frm3" />
<button>Enviar frm3</button>
</form>
If it is to send it to Ajax, you can have another function that sends the requests to Ajax, and from within on.click
you pick up the form and pass it to that function.
To make the code more fl exible, you can give each form a action
attribute where you would place the file you want to invoke in the Ajax request and a method
attribute. Then you use prop
of the form object to know which file should be sent according to the form that is.
The function that the Ajax request would make would be more or less:
function enviarAjax(frm)
{
var data=frm.serialize();
var request = $.ajax
({
url: frm.prop('action'), //Lo toma del form
method: frm.prop('method'), //Lo toma del form
data: data,
dataType: 'html' //o 'json' ...
});
request.done(function( msg )
{
console.log(msg);
return msg; //En caso de que sea necesario manejar los reusltados
});
request.fail(function( jqXHR, textStatus )
{
alert( 'Error en la petición: ' + textStatus );
var msg={error: textStatus};
return msg;
});
}
And the code of on.click
would be almost the same, it would only include the call to this method:
$('button').on('click', function(e) {
e.preventDefault();
var frm = $(this).closest('form');
var data = enviarAjax(frm); //Aquí se recibe data desde el return de la función
console.log(data);
alert('Enviaste el formulario con id: '+frm.prop('id'));
});
Note: All code should go within a block $(function() { ... });