0

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

1
  • You need to check each field, you can't do this with a single selector. Commented May 22, 2013 at 13:44

5 Answers 5

10

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/

Sign up to request clarification or add additional context in comments.

15 Comments

Any reason to use length instead of: $.trim(this.value) === "" ?
It could probably even be return !$.trim(this.value);
@Ian It couldn't be that. Remember about "0".
@VisioN Not true. Try it :) "0" is truthy - the only falsey string is "". It's different when comparing to a boolean
@Ian Haha! Regarding these JS-tricks, I just remembered that question. After all we should be professors here, but still are mixing the things :)
|
2
$('.enter-info--ownerInfo .req').each(function() {

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

});

Comments

1

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
}

Comments

0

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
}

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.