0

I have a class .address added to a couple of my inputs. Basically, I want to check if all of them have been filled out. I know this is possible by iterating over the class like this:

var valueForAll = true;
$('.address').each(function (i, obj) {
    if ($(this).val() == "") {
        valueForAll = false;
    }
});
if (valueForAll == true) {
    // Do something
}
else {
    // Do something else
}

I don't think this is an ideal solution though. So I found the :empty selector. Which works like this:

$("input:empty").length == 0;

However, doing this for my class always shows a length of 6. I don't know why.

$(".address:empty").length == 0;

Edit:

This is not a duplicate question as this one attached from @chrispbacon. This question focuses on how to check if all inputs of a class have been filled, not all elements inside a div. I cannot find any thread on Stack Overflow that focuses on how to check if all inputs have a value of a class without iterating over the class.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

1 Answers1

1

https://developer.mozilla.org/en-US/docs/Web/CSS/:empty

:empty

Is used to find elements that have no children. Not for inputs that do not have a value.

https://developer.mozilla.org/en-US/docs/Web/CSS/:blank

:blank

Is an up and coming pseudoselector for empty inputs, but coverage is still being added for browsers.

Taplar
  • 24,788
  • 4
  • 22
  • 35
  • Thanks for your answer. Could you please reopen my question, as this is not a duplicate. See my edit explaining my reasoning. – Tom el Safadi Jun 19 '19 at 21:42
  • Unfortunately, it has to work in all browsers. Can you think of any other way of checking if all inputs of a class have a value without iteration? – Tom el Safadi Jun 19 '19 at 21:44
  • The duplicate does cover your case. A filter on the inputs would also do the same thing. `$('input').filter(function(){ return !this.value.trim(); }) === 0` – Taplar Jun 19 '19 at 21:44
  • I don't need it on all my inputs. I need it only on the inputs inside the class. – Tom el Safadi Jun 19 '19 at 21:47
  • So select just the ones you want to check. That is a small detail. – Taplar Jun 19 '19 at 21:47