0

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
  }
  }
}
Beep
  • 2,737
  • 7
  • 36
  • 85
  • 1
    please provide the html also – tuhin47 Aug 02 '19 at 16:10
  • Its just a basic form – Beep Aug 02 '19 at 16:11
  • 1
    Regardless of it being a basic form or not, having a *runnable* [mcve] helps others generate solutions for you – charlietfl Aug 02 '19 at 16:13
  • Meaby you want to try something diferent, instead of making an interval, create event listener for change in the fields that you want to check! Also you can check multiple fields like this: if(document.getElementById('Email').value.trim() != "" && document.getElementById('...').value.trim() != "" ){ hideDivs() } else { displayDivs()}; or if ([listOfInputs].filter(input => !document.querySelector(input).value || document.querySelector(input).value.trim() == "").length > 0) {showDivs()} else {hideDivs()} – ithan Aug 02 '19 at 16:19
  • @ithan Please don't post long code blobs as answers in comments. Extremely hard to read and just adds extra noise. Create an answer with it instead – charlietfl Aug 02 '19 at 16:21

3 Answers3

1

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; }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

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
    }
}
Nathan Fries
  • 1,464
  • 5
  • 15
0

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

gaurav soni
  • 206
  • 1
  • 10