0

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;
}

1 Answer 1

2

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()

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

6 Comments

when all are empty it should return false. When at least one is not empty true
So just check if empty > 0
or if (empty === 64) return false; Thanks anyway
@GragasIncoming I would advise against doing it that way. If you add or remove an input in the HTML, you break your JS code.
@GragasIncoming, if you want to get the total count of the input, you can $('#Matrix1 input').length, instead of hardcoding the value
|

Your Answer

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