How to send a form automatically when inputs are completed?

Asked

Viewed 1,250 times

2

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

My form is 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 is a simple form with two inputs and I want to send it without having to put submit button, I want to send when lose focus.

  • Do not do this, think about your users. S and the guy type something wrong, or just click unintentionally you will already submit the wrong data? And how will you validate if you just filled it out? If it is when the field loses focus the guy can start typing and click off the form atoa and send unintentionally... would not recommend this

2 answers

3


You can wait for the event blur in the inputs and if both are with a defined value, 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 the time when the form was sent. In your case, you would send the form by replacing the alert() for document.getElementById('form1').submit();.

  • Perfect friend! Thanks for your help!

1

Look, you don’t need Javascript to accomplish this, you can use the tag required.

<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>

  • Thank you for answering friend! But I don’t want you to have a Ubmit button on the form, just the two inputs, and when it fills both and exits the input, send the form

  • @user41251, I see someone here has been missing UX classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.