0

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?

6
  • 2
    possible duplicate of jQuery check if any of selected inputs is empty Commented Jul 19, 2013 at 17:13
  • 3
    @Neal It's not a duplicate, it's the opposite. Commented Jul 19, 2013 at 17:15
  • @Barmar not really... looks exactly the same, with the same answers... Commented Jul 19, 2013 at 17:16
  • @Neal - is oposite - the second one tests for "if any empty" and this tests for "if all empty" Commented Jul 19, 2013 at 17:17
  • 2
    @Barmar any and all are not opposites Commented Jul 19, 2013 at 17:17

3 Answers 3

3

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

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

Comments

2

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;

1 Comment

@Ankit Thanks, you're correct. I fixed the same typo in the other answer now.
0

You can try

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

1 Comment

I think the part he's having trouble with is what something should be to get his true/false result.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.