Jquery loop form to check for all empty fields then execute a function

I'm trying to loop form to check for empty field and then execute and function. I'm currently using something like this below that I found on this website but what is happening that the each loop check 1 field and see 1 that not empty and still execute else function. I think I need to check all at once then execute next function. How could I achieve this?

if($('.enter-info--ownerInfo .req').val() != "") {
   alert("Empty Fields!!")
    } else {
    run this function
    }  

Thanks...

Answers:

Answer

Use filtering, it is easy:

var anyFieldIsEmpty = $("form :input").filter(function() {
        return $.trim(this.value).length === 0;
    }).length > 0;

if (anyFieldIsEmpty) {
    // empty fields
}

DEMO: http://jsfiddle.net/Lz9nY/

Answer
$('.enter-info--ownerInfo .req').each(function() {

  if ($(this).val() == "")
  {
     alert("empty field : " + $(this).attr('id'));
  }

});
Answer

Start by selecting all your fields:

var fields = $('.enter-info--ownerInfo .req')

Then filter them down to the ones with an empty value:

fields.filter(function() {
    return this.value === '';
});

Then check the length property of the resulting object. If it's equal to 0 then all fields have a value, otherwise you execute your function.

if(fields.length === 0) {
    // no empty fields
}
else {
    // empty fields
}
Answer

You can use a loop and flag:

var valid = true;
$('.req').each(function () {
    if ($(this).val() == '') {
        valid = false;
        return false;
    }
});

if (valid) {
    // all fields are valid
}
Answer

You can use .filter method to reduce the elements to those matching your criteria:

if $('.enter-info--ownerInfo .req').filter(function () {
  return $.trim($(this).val()) == ""
}).length > 0) {
  alert("One or more fields are empty")
} else {
  // run this function
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.