jvk jvk - 4 months ago 15
jQuery Question

How to do for loop for display all errors at once in JavaScript?

I am currently working on JavaScript form validation. For individual it is applying all errors but my task is to loop all element at once and display error at once. Is there any solution.

<form action="" id="register" onsubmit="return validation()">
Name<input type="text" id="name">
<p id="error"></p>
Email<input type="text" id="email">
<p id="error"></p>
Password<input type="text" id="password">
<p id="error"></p>
<input type="submit" name="submit" value="Submit">
</form>
<script>
function validation() {
if (document.getElementById('name').value=="") {
document.getElementById("error").innerHTML="Please fill your name";
}
and so.. on..
}
</script>


Can anyone help me how to for loop all errors to display at once when user click submit buttton?

Answer

First the id should be unique in same document so you have to replace duplicate ones by classes, e.g :

 Name<input type="text" id="name">
 <p class="error"></p>

 Email<input type="text" id="email">
 <p class="error"></p>

 Password<input type="text" id="password">
 <p class="error"></p>

Then just show the error message of the input in the related .error paragraph :

function validation() {
   if ($('#name').val()==="") {
       $('#name').next(".error").html("Please fill your name");
   }
}

Hope this helps.

$('#register').on('submit', function(){
  var submit = true;

  if ($('#name').val()===""){
    $('#name').next(".error").html("Please fill your name");
    submit = false;
  }else
    $('#name').next(".error").html("");


  if ($('#email').val()===""){
    $('#email').next(".error").html("Please fill your email");
    submit = false;
  }else
    $('#email').next(".error").html("");

  if ($('#password').val()===""){
    $('#password').next(".error").html("Please fill your password");
    submit = false;
  }else
    $('#password').next(".error").html("");

  if ($('[name="check"]:checked').length===0){
    $('[name="check"]:last').next(".error").html("Please fill your password");
    submit = false;
  }else
    $('[name="check"]').next(".error").html("");
  
  return submit;
})
.error{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="register" id="register">
  Name <input type="text" id="name">
  <p class="error"></p>

  Email <input type="text" id="email">
  <p class="error"></p>

  Password <input type="text" id="password">
  <p class="error"></p>

  Checkboxes 
  <br>
  <input type="checkbox" name="check" value="check_1">check 1
  <br>
  <input type="checkbox" name="check" value="check_2">check 2
  <br>
  <input type="checkbox" name="check" value="check_3">check 3
  <p class="error"></p>
  
  <input type="submit" name="submit" value="Submit">
</form>