Skip to content

Check if all inputs are empty

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

Answer

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.