简体   繁体   中英

getElementById check multiple conditions

I am trying to build a function that checks if all fields are populated, if populated then show div if not hide.

I can get this to work on one fields however i have then tried two ways of checking multiple.

first if first condition met I then ran other condition checking second field nested inside the first... this done not work.

second I passed in an array of ID's rather than a single... this did not work either..

I am left with a working function that only works if first filed is populated can anyone think of a solution to this or maybe i passed in my array incorrectly.

My code

var myVar = setInterval(myTimer, 10);

function myTimer() {

if(!document.getElementById('Email').value) { // I need this to pass if multiple id's
          var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
            for(var i = 0; i < divsToHide.length; i++){
                divsToHide[i].style.visibility = "hidden"; // or
                divsToHide[i].style.display = "none"; // depending on what you're doing

        }
    }
  else {
   var divsToHide = document.getElementsByClassName("somediv"); //divsToHide is an array
            for(var i = 0; i < divsToHide.length; i++){
                divsToHide[i].style.visibility = "visible"; // or
                divsToHide[i].style.display = "block"; // depending on what you're doing
  }
  }
}

Make it so your function takes an argument of the element ID and the class Name you need to check for.

Also, never use .getElementsByClassName() ( read here for why ). Instead, use .querySelectorAll() .

And, you can use the modern .forEach() API of arrays and node lists (not in IE though), which is simpler than managing traditional for loops with indexes.

Lastly, use pre-made CSS classes instead of inline styling.

 // You just need to pass the ID and Class to the following line var myVar = setInterval(function(){ myTimer([id here],[class here]) }, 10); function myTimer(id, class) { // Set up these references just once and the rest of the code // will be easier to read var elem = document.getElementById(id); var divsToHide = document.querySelectorAll("." + class); // Instead of negative logic, reverse the if branches if(elem.value) { divsToHide.forEach(function(){ this.classList.remove("hidden"); // Much simpler than inline styling }); } else { divsToHide.forEach(function(){ this.classList.add("hidden"); }); } 
 /* Use pre-made CSS classes instead of inline styling */ .hidden { display:none; } 

If you have an array of the IDs such as

let idArray = ['foo', 'bar', 'baz']

You can iterate through an array using a for loop

for (i = 0; i > idArray.length; i++) {
    if (!document.getElementById(idArray[i]).value) { 
        // your hide logic
    } else {
        // your show logic
    }
}

You can create a const of all elements that need to validate. For example,

const elementIdsToBeValidated = ['name', 'email'];

You can also create validator functions that returns true and false based on input,

const nameValidator = (val) => !!val;
const emailValidator = (email) => !!email;

const validators = [nameValidator, emailValidator];

Then you can run your timer function,

var myVar = setInterval(myTimer(['name', 'email']), 10);

function myTimer(ids) {
  ids.forEach(id => {
    const el = document.getElementById(id);
    const val = el.value;
    const divEl = document.getElementById('error');
    const valid = validators.reduce((acc, validator) => validator(val), false);
    if(valid) {
      divEl.style.display = 'none';
    } else {
      divEl.style.display = 'block';
    }
  });
}

You can look at this stackBlitz example, https://stackblitz.com/edit/js-ie7ljf

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