最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if all inputs are empty - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question asked Nov 14, 2014 at 14:04 JohnJohn 3,78914 gold badges44 silver badges49 bronze badges 1
  • show us how you've made the info div appear – DannyTheDev Commented Nov 14, 2014 at 14:06
Add a ment  | 

2 Answers 2

Reset to default 12

Loop through all the inputs, and if you get to a non-empty one you know they're not all empty. If you plete 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 paring (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.

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

发布评论

评论列表(0)

  1. 暂无评论