Pickles Pickles - 4 months ago 9
HTML Question

How to check if form is filled up in jquery?

I have a form and a submit button and a modal. I want to run the modal to show a message if the form has an empty value.

I tried .each to loop and check the form for empty inputs but even when the form is filled up it still returns as empty.

My html form:

<form id="register_form" role="form" >
<label >First Name</label>
<input id="inN"data-error="Enter first name." required>
<div class="help-block with-errors"></div>
</div>
<label>Last Name</label>
<input id="inL" data-error="Enter last name." required>
<div class="help-block with-errors"></div>
</div>
</div>
<label for="inputEmail" class="control-label">Email</label>
<input type="email" class="form-control" id="inputEmail" data-error="Enter email." required>
<div class="help-block with-errors"></div>
</div>
</div>
</form>


This is my javascript:

$('#register_form').each(function() {
if ( $(this).val() === '' ){
console.log($(this).val()); // empty even when form is not
vm.message = 'One or Two fields are empty. Please fill up all fields'
document.getElementById("message").textContent=vm.message; // message on the modal
};


});

Answer

You have to use $('#register_form input').each instead of $('#register_form').each to loop through all the input fields present in form.

Please note that, if you have select box or textarea fields in your real form then this code needs to be modified accordingly. I will also suggest you to look at JQuery Validate plugin which do all these work for you.

$(document).ready(function() {

  $("#submitButton").click(function() {
    ValidateForm();
  });

});

function ValidateForm() {

  var formInvalid = false;
  $('#register_form input').each(function() {
    if ($(this).val() === '') {
      formInvalid = true;
    }
  });

  if (formInvalid)
    alert('One or Two fields are empty. Please fill up all fields');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="register_form" role="form">
  <label>First Name</label>
  <input id="inN" data-error="Enter first name." required>
  <div class="help-block with-errors"></div>
  </div>
  <label>Last Name</label>
  <input id="inL" data-error="Enter last name." required>
  <div class="help-block with-errors"></div>
  </div>
  </div>
  <label for="inputEmail" class="control-label">Email</label>
  <input type="email" class="form-control" id="inputEmail" data-error="Enter email." required>
  <div class="help-block with-errors"></div>
  </div>
  </div>
  <button id="submitButton">Submit</button>
</form>