简体   繁体   中英

jquery check multiple inputs for value

<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

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.

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