0
<form class=".form" action="">
  <input type="text" class="inputs"><br>
  <input type="text" class="inputs"><br>
</form>
<button>Check</button>


$("button").on("click", function () {
  if($(".inputs").val()) {
    $("body").css("background-color", "yellow");
  } else {
    $("body").css("background-color", "red");
  }
});

As you may see, I want to check for a value in inputs and based on that select a color for a body. The problem is, it checks only the first element among all of them.

You can try to enter a value in the second input and leave the first one empty and see this.

I want to check all of the inputs for a value with AND condition, how do I do this?

Thanks

2
  • 3
    What happens if someone enters values in both? Commented Apr 23, 2018 at 17:14
  • 1
    the background should change to yellow :) Commented Apr 23, 2018 at 17:16

1 Answer 1

3
var $inputs = $('.inputs');
//logical OR, if any have a value
$inputs.filter(function(){ return this.value.trim(); }).length
//logical AND, if none of them do not have a value
$inputs.filter(function(){ return !this.value.trim(); }).length < 1
//logical AND, with just nots (!)
!$inputs.filter(function(){ return !this.value.trim(); }).length

This will return inputs that have a non blank value. A length of > 0 being truthy.

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

1 Comment

This is awesome, to be honest. Even tho it doesn't really solve my problem(based on the above condition it would present OR instead of AND logic)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.