Marcin Bobowski
Marcin Bobowski

Reputation: 1765

jQuery check if all of selected inputs are empty

What is the simplest way to test if all of selected inputs are empty?

I get my inputs this way:

$myinputs = $('.inputstotest');

and would test single input with:

if ( $.trim($this.val()) == '' )

but how to test a group and return true if all are empty or false if any (at least one) is not empty?

Upvotes: 0

Views: 928

Answers (3)

Barmar
Barmar

Reputation: 780724

This is just like my answer to the previous question, except the sense of the test is reversed.

var result = true;
$('.inputstotest').each(function() {
    if ($.trim($(this).val())) != '') {
        result = false;
        return false; // Terminate the .each loop
    }
});
return result;

Upvotes: 2

palaѕн
palaѕн

Reputation: 73896

Try this:

var $myinputs = $('.inputstotest');

var allEmpty = $myinputs.filter(function () {
    return $.trim(this.value) != '';
}).length == 0;

console.log(allEmpty);

FIDDLE DEMO

( In order to test, enter some values in the HTML markup, run the fiddle again and check in the console.)

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

You can try

$(".inputstotest input").each(function(){
        if ($.trim($(this).val()).length == 0){
          //do something
        }
        else{
             //do something
        }
    });

Upvotes: 0

Related Questions