Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check all input values of same class is empty jquery

Here I have many input text fields with same class like

<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>

My requirement is to check wheather all input fields of this class is empty or not. I've tried this

if(!('.MyClass').val()){
alert("empty");
}

But it doesn't make any result. Can anyone help?

like image 644
tvshajeer Avatar asked Feb 13 '15 06:02

tvshajeer


People also ask

How do you check if all inputs are not empty with jQuery?

Just use: $("input:empty"). length == 0; If it's zero, none are empty.


3 Answers

You can check

$('button').click(function() {
  var $nonempty = $('.MyClass').filter(function() {
    return this.value != ''
  });

  if ($nonempty.length == 0) {
    alert('empty')
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>

Or using a flag

$('button').click(function() {
  var flag = false;
  $('.MyClass').filter(function() {
    if (this.value != '') {
      flag = true;
      //no need to iterate further
      return false;
    }
  });

  if (!flag) {
    alert('empty')
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
like image 112
Arun P Johny Avatar answered Oct 16 '22 12:10

Arun P Johny


You can compare the length of number of input with number of empty input using :

var allemptylength=$(".MyClass").filter(function() {
    return this.value.length !== 0;
})});

if($('.MyClass').length== allemptylength.length){
  alert("all empty");
}

Working Demo

like image 27
Milind Anantwar Avatar answered Oct 16 '22 12:10

Milind Anantwar


To make sure each classes are checked, use

$.each($('.MyClass'),function() {
   if ($(this).val().length == 0) {
    alert('empty');
   }
});
like image 43
slashsharp Avatar answered Oct 16 '22 12:10

slashsharp