繁体   English   中英

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

[英]How to check all input has value and 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');

我正在检查它们是否有价值

 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按钮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) 
})

现在当所有输入都有价值时如何做某事;

我尝试了else if()但它给出了不正确的结果,例如当第一个输入不值时,它不会将inputErrorBorder class 添加到第二个或第三个输入。

请帮忙;

将其添加到当前设置的最简单方法之一是将标志变量添加到checkEmpty function 并返回该值。 然后在EventListener中处理结果

带有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;
}

使用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