I have a problem in the message that is printed from the validation of my form, it only prints correctly when the last field is not filled or is filled, ie the problem is in the execution of the loop. Here is my HTML code:
<form id="formulario">
<div class="form-group">
<label class="control-label">Nome Completo</label>
<input id="nomeCompleto" type="text" name="nome" class="form-control" maxlength="40" onkeypress="return letras()">
</div>
<div class="form-group">
<label class="control-label">Modelo do Veículo</label>
<input id="modeloDoVeiculo" type="text" name="modelo" maxlength="40" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Placa do Veículo</label>
<input id="placaDoVeiculo" type="text" name="placa" class="form-control" maxlength="8">
</div>
<div class="alert text-center" id="apareceAlerta" style="display:none"></div>
<div class="form-group text-center">
<input type="submit" name="adicionar" value="Adicionar" class="btn btn-primary" onclick="alertaCadastro()">
</div>
</form>
And my JavaScript code:
var formulario = document.getElementById("formulario");
formulario.addEventListener("submit",cadastrarVeiculo);
function cadastrarVeiculo(evento){
evento.preventDefault();
for(var i = 0; i < this.elements.length; i++){
var elemento = this.elements[i];
if (elemento.type != "submit") {
alertaDeCadastro = document.getElementById("apareceAlerta");
let isValid;
if (elemento.value == "") {
elemento.parentNode.classList.add("has-error");
alertaDeCadastro.classList.remove("alert-success");
alertaDeCadastro.classList.add("alert-danger");
alertaDeCadastro.innerHTML = "Os campos acima não foram preenchidos corretamente!";
alertaDeCadastro.style.display = "block";
}else{
elemento.parentNode.classList.remove("has-error");
alertaDeCadastro.classList.remove("alert-danger");
alertaDeCadastro.classList.add("alert-success");
alertaDeCadastro.innerHTML = "Cadastro realizado com sucesso!";
alertaDeCadastro.style.display = "block";
}
}
}
}