Question :
I would like to send a form
without clicking the submit
button, using the click event of jQuery, I tried that way but did not succeed:
$(document).ready(function() {
$('.item').click(function() {
var id = $(this).attr('rel');
var form = $("#form_" + id);
form.submit(function() {
alert('pronto!');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><formid='form_7'action="" method='POST'>
<input type='text'>
</form>
</div>
<button class='item' rel='7'>Botão</button>
Thank you in advance
Answer :
Two problems:
- removes the
#
from the ID attribute in the HTML. It should be onlyid="form_7"
and notid='#form_7'
- the submit method does not accept arguments, it should only be
form.submit();
jsFiddle: link
I created something more generic that works like for
of label
To use just create
-
button[type="submit"]
orinput[type="submit"]
or.submit
- Add a
for
attribute with the id of the form you want to send.
// Alerta para mostrar que o form foi enviado
$('body').on('submit', 'form', function(e){
e.preventDefault();
alert($(this).find('input[name="value"]').val());
});
// Evento de envio de form
// Funciona com 'button[type="submit"]', 'input[type="submit"]', '.submit'
$('body').on('click', 'button[type="submit"], input[type="submit"], .submit', function(){
var id = this.getAttribute('for');
var form = $('form[id="'+id+'"]');
if(form.size()>0){
form.submit();
}
});
.submit{
border: solid 1px #084884;
border-radius:2px;
cursor:pointer;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formid="teste1">
<input name="value" type="text" value="1"/>
</form>
<form id="teste2">
<input name="value" type="text" value="2"/>
</form>
<form id="teste3">
<input name="value" type="text" value="3"/>
</form>
<ul>
<li><input type="submit" for="teste1" value="Enviar Form 1"/></li>
<li><input type="submit" for="teste2" value="Enviar Form 2"/></li>
<li><input type="submit" for="teste3" value="Enviar Form 3"/></li>
</ul>
<span class="submit" for="teste2">Enviar Form 2</span>
You can do this via Javascript …
First create a javascript function that will get your form by ID and submit.
ex:
function submete() {
document.getElementById('IDDOSEUFORM').submit();
}
And after that, add an action on the click on your button, the onclick function calling the javascript method.
ex:
<button class='item' rel='7' onclick="submete();">Botão</button>