4

I have multiple inputs on my page, when any them are filled, an "info div" appears on the side; Now if all the inputs are manually cleared (on keyup), I need to hide that "info div".

How can I check (on keyup) that all of the inputs are empty at the same time?

Cheers

John
  • 3,529
  • 14
  • 42
  • 48

2 Answers2

12

Loop through all the inputs, and if you get to a non-empty one you know they're not all empty. If you complete your loop without finding one, then they are all empty.

function isEveryInputEmpty() {
    var allEmpty = true;

    $(':input').each(function() {
        if ($(this).val() !== '') {
            allEmpty = false;
            return false; // we've found a non-empty one, so stop iterating
        }
    });

    return allEmpty;
}

You might want to 'trim' the input value before comparing (if you want to treat an input with just whitespace in it as empty). You also might want to be more specific about which inputs you're checking.

Shai
  • 7,159
  • 3
  • 19
  • 22
  • 1
    You can short cut the loop and return as soon as on input field is filled in, like `if ($(this).val() !== '') { return false; }` – dsuess Nov 14 '14 at 14:10
  • @dsuess Updated. Thanks. (Although your example isn't quite enough: we can't `return false` the outer function from inside the inner one! We instead set `allEmpty = false`, then return `false` to tell `$.each` to stop iterating.) – Shai Nov 14 '14 at 14:18
3

Simple solution (ES6) Without jQuery

html

<div class="container">
  <input id="input1" />
  <input id="input2" />
  <input id="input3" />
</div>

JS

document.getElementById('btnCheckEmpty').addEventListener('click', () => {
        if (isEveryInputEmpty())
            alert('empty');
        else
            alert('not empty');
});


const isEveryInputEmpty = () => {
    var inputs = document.querySelectorAll('.container input');
    
    for (const input of inputs)
        if (input.value !== '') return false;
    
    return true;
}

Online Demo

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55