简体   繁体   中英

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...

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/

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

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

});

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
}

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
}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM