submit a form with jQuery by clicking a button outside the form

3

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

    
asked by anonymous 22.11.2016 / 19:39

3 answers

5

Two problems:

  • removes the # from the ID attribute in the HTML. It should be only id="form_7" and not id='#form_7'
  • the submit method does not accept arguments, it should only be form.submit();

jsFiddle: link

    
22.11.2016 / 19:48
2

I created something more generic that works like for of label

To use just create

  • button[type="submit"] or input[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>
    
22.11.2016 / 20:32
1

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>
    
22.11.2016 / 19:47