user9402741
user9402741

Reputation:

checking if multiple input values are not empty

I have a table with 64 inputs and i want to check if all input values inside table #Matrix are not empty. If at least one input value is not empty then we are okay. Below is what i am trying.

It only returns true if only the very first input is not empty.

if (!$('table #Matrix1 input').val()) {
    console.log("Empty");
    return false;
}

Upvotes: 0

Views: 1167

Answers (1)

Eddie
Eddie

Reputation: 26854

One option is to use .filter to filter the empty inputs. This will give the length of the empty inputs. Like:

var empty = $('#Matrix1 input').filter(function() {
    return this.value.trim() === ''; //Get the value and trim. Return true if equals to an empty string
}).length;

Here is a snippet.

$('[type="button"]').click(function() {

  var empty = $('#Matrix1 input').filter(function() {
    return this.value.trim() === '';
  }).length;

  //console.log(empty);

  if ( $('#Matrix1 input').length === empty ) console.log('All are empty. Return false.');
  else console.log('Not all are empty');

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='Matrix1'>
  <input type="text" value='1'>
  <input type="text" value='1'>
  <input type="text" value='1'>
  <input type="text" value='            '>
  <input type="text" value='     '>
  <input type="text" value=''>
</div>
<button type="button">Click Me!</button>

Doc: .filter()

Upvotes: 2

Related Questions