简体   繁体   中英

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.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.

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. Then process the results in the EventListener

checkEmpty With hasEmpty Flag

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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