Oo'-
Oo'-

Reputation: 236

I can not trigger the alert when the form is empty after developing a clean code in pure JavaScript

The small code in pure HTML, without forgetting to set the method for get:

        <form action="#" method="get">
          <input id="name" type="text" name="name" placeholder="Nome"><br>
          <input id="email" type="text" name="email" placeholder="E-mail"><br>
          <textarea id="message" name="name"  rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio"></textarea>
          <input type="submit" value="Enviar" id="send"><br>
        </form>

I refactored and made a clean code of the dirty multiple if-else statements, simplifying. After it, I can not trigger the alert.

The code let send = document.getElementById("send"); checks the code <input type="submit" value="Enviar" id="send"><br>.

Before, in a dirty code, I had many document.getElementById("email").value == "" and simplified to:

const fields = new Set([
  'name',
  'email',
  'message',
]);

I simplified three 'if-else statements along with these if-else statements of identifiers. Firstly, it will check if the fields are empty, go to verify the length, 1 indicates only an empty field and > 1 indicates more empty fields. Else they will check the fields are full and submit.

function alert() 
{
  let required = fields.value == "";

  if (required.length == 1)
  {
    alert("The field is required!");
    required = []
  }

  else if (required.length > 1)
  {    alert("The fields are required!");
      required = []
  }

  else
  {
    document.getElementById("send").submit();
    alert("Thank you! The message was sent successfully")
  }
}

Finally, the code send.addEventListener("click", alert) indicates to click the function when sending, and addEventListener will trigger the alert.

Complete code in JavaScript:

let send = document.getElementById("send");
const fields = new Set([
  'name',
  'email',
  'message',
]);

function alert() 
{
  let required = fields.value == "";

  if (required.length == 1)
  {
    alert("The field is required!");
    required = []
  }

  else if (required.length > 1)
  {    alert("The fields are required!");
      required = []
  }

  else
  {
    document.getElementById("send").submit();
    alert("Agradecemos, mensagem enviada com sucesso!")
  }
}

send.addEventListener("click", alert)

Upvotes: 0

Views: 64

Answers (2)

chrwahl
chrwahl

Reputation: 13080

I will suggest that you create an event listener for invalid on the form. This will be called when one of the required fields empty/invalid (see the required attribute on all the fields). I made a custom alert that shows.

var alert = document.getElementById('alert');

alert.addEventListener('click', e => {
  if (e.target.nodeName == 'BUTTON')
    alert.classList.remove('show');
});

document.forms.form01.addEventListener('submit', e => {
  console.log('The form will submit');
});

document.forms.form01.addEventListener('invalid', e => {
  e.preventDefault();
  alert.classList.add('show');
}, true);
#alert {
  display: none;
}

#alert.show {
  display: block;
}
<form name="form01" action="#" method="get">
  <input id="name" type="text" name="name" placeholder="Nome" required><br>
  <input id="email" type="text" name="email" placeholder="E-mail" required><br>
  <textarea id="message" name="message" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio" required></textarea>
  <input type="submit" value="Enviar" id="send"><br>
</form>
<div id="alert">The fields are required! <button>OK</button></div>

This is overruling the default behavior in the browser. In any case I think the required attribute is the right way to go.

Upvotes: 1

Nicholas Mberev
Nicholas Mberev

Reputation: 1841

You may like to do something like this with your function:

 function showAlerts(){
    var allInputs = document.querySelectorAll('#name, #email, #message');
    if(null != allInputs){
     for(var i in allInputs){
        if(!isNaN(i)){
          // here you can check for values, emptiness etc
          if(allInputs[i].value.trim() === ''){
             // this field is empty
             alert('This field is required!');
          }
          ...
       }
     }
    }
  }

Upvotes: 0

Related Questions