简体   繁体   English

如何检查所有输入是否有价值并做某事

[英]How to check all input has value and do something

i have these inputs and i wanted to check every one of them has value then do something;我有这些输入,我想检查它们中的每一个是否有价值然后做点什么;

const tch_family_name = document.getElementById('tch_family_name');
const tch_lastname = document.getElementById('tch_lastname');
const tch_name = document.getElementById('tch_name');
const tch_phone = document.getElementById('tch_phone');
const first_alph = document.getElementById('first_alph');
const second_alph = document.getElementById('second_alph');
const third_alph = document.getElementById('third_alph');
const tch_bday = document.getElementById('tch_bday');
const textarea1 = document.getElementById('textarea1');

and I'm checking they have value or not like this我正在检查它们是否有价值

 function checkEmpty(check) {
        for (i = 0; i < check.length; i++) {
            if (check[i].value == "" || check[i].value == " " || check[i].value == null) {
                check[i].classList.add('inputErrorBorder')
            } else {
                check[i].classList.remove('inputErrorBorder')
            }
        }
    }

//mainInfo button id //mainInfo按钮id

  mainInfo.addEventListener('click', () => {
            test = [tch_family_name, tch_lastname, tch_name, tch_phone, first_alph, second_alph, third_alph, tch_bday, textarea1]
            checkEmpty(test) 
})

now how to do something when all input have value;现在当所有输入都有价值时如何做某事;

I tried else if() but it gave an incorrect result for example when first input don't value then it wont add inputErrorBorder class to a second or third inputs.我尝试了else if()但它给出了不正确的结果,例如当第一个输入不值时,它不会将inputErrorBorder class 添加到第二个或第三个输入。

Please help;请帮忙;

One of the easiest ways to add this to your current setup is to add a flag variable to the checkEmpty function and return that value.将其添加到当前设置的最简单方法之一是将标志变量添加到checkEmpty function 并返回该值。 Then process the results in the EventListener然后在EventListener中处理结果

checkEmpty With hasEmpty Flag带有checkEmpty标志的hasEmpty

function checkEmpty(check) {
    let hasEmpty = false;
    for (let i = 0; i < check.length; i++) {
        if (check[i].value === "" || check[i].value === " " || check[i].value == null) {
            check[i].classList.add('inputErrorBorder');
            hasEmpty = true;
        } else {
            check[i].classList.remove('inputErrorBorder');
        }
    }
    return hasEmpty;
}

Using hasEmpty flag from checkEmpty使用hasEmpty中的checkEmpty标志

mainInfo.addEventListener('click', () => {
    let test = [tch_family_name, tch_lastname, tch_name, tch_phone,
        first_alph, second_alph, third_alph, tch_bday, textarea1];
    let hasEmpty = checkEmpty(test);
    if (!hasEmpty) {
        // All Have Value
    } else {
        // Something has missing value
    }
})

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

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