简体   繁体   English

检查所有输入是否为空

[英]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; 我的页面上有多个输入,当它们被填充时,侧面会出现“info div”; Now if all the inputs are manually cleared (on keyup), I need to hide that "info div". 现在如果所有输入都被手动清除(在keyup上),我需要隐藏“info div”。

How can I check (on keyup) that all of the inputs are empty at the same time? 如何检查(在密钥上)所有输入同时为空?

Cheers 干杯

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. 您还可能希望更具体地了解您正在检查哪些输入。

Simple solution (ES6) 简单的解决方案(ES6)

html HTML

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

JS JS

function areAllInputsEmpty() {
  return $(".container input").filter(function() {
    return $.trim($(this).val()).length > 0
  }).length == 0;
}

Online demo (jsFiddle) 在线演示(jsFiddle)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM