How to submit a form automatically when the inputs are filled out?

1

I have two input in a form, which is actually a score of a game. I want you to send this board with focusout() when the user populate the two fields of form .

My form looks like this:

<form method="post" id="form1" action="teste2.php">
  <label>Time1</label>
  <input type="text" name="gols1" id="gols1">
  <label>Time2</label>
  <input type="text" name="gols2" id="gols2">
</form>

It's a simple form with two inputs and I want to send it without having to put submit button, I want it to send when I lose focus.

    
asked by anonymous 23.02.2016 / 19:11

2 answers

2

You can wait for the blur event on the inputs and if both are set, the form will be submitted.

(function() {

  var $gols1 = document.getElementById('gols1'),
      $gols2 = document.getElementById('gols2');

  function handleSubmit(){
    if ($gols1.value && $gols2.value)
      alert('Formulário enviado.');
  }

  $gols1.addEventListener('blur', handleSubmit);
  $gols2.addEventListener('blur', handleSubmit);
})();
<form method="post" id="form1" action="teste2.php">
  <label for='gols1'>Time1</label>
  <input type="text" name="gols1" id="gols1">
  <label for='gols2'>Time2</label>
  <input type="text" name="gols2" id="gols2">
</form>

In the example I put a alert() only to show when the form was sent. In your case, you would submit the form by replacing alert() with document.getElementById('form1').submit(); .

    
23.02.2016 / 23:31
1

Look, you do not need JavaScript to accomplish this, you can use the required tag.

<form method="post" id="form1" action="teste2.php">
  <div>
    <label for="gols1">Time1</label>
    <input type="text" name="gols1" id="gols1" required />
  </div>
  <div>
    <label for="gols2">Time2</label>
    <input type="text" name="gols2" id="gols2" required />
  </div>
  <div>
    <input type="submit" name="enviar" id="enviar">
  </div>
</form>
    
23.02.2016 / 21:00