Home > Software engineering >  Unable to toggle div display using Javascript
Unable to toggle div display using Javascript

Time:09-14

I have written some vanilla JS in order to hide/display some divs, depending on the value of one of the fields in them.

My problem is that, while hiding them appropriately is working by default, trying to make them appear again, I am having issues as using getElementById is returning nulls.

I've googled and found numerous examples where similar code has worked and I cannot figure out why mine isn't actually working.

The JS I've written is below:

var hidden = false
document.addEventListener("keypress", function(event) {
  if (event.key == '`') {
    if (hidden == false) {
      resultEntries = document.getElementsByClassName('result-row');
      for (i = 0; i < resultEntries.length   1; i  ) {
        var x = document.getElementById('root_cause_'   i)
        if (x != null) {
          var value = x.options[x.selectedIndex].value;
          console.log('value'   value)
          if (value == '') {
            row = document.getElementById('line_'   i)
            row.style.display = 'none';
          }

        }
      }
      hidden = true
    } else {
      resultEntries = document.getElementsByClassName('result-row');
      for (i = 0; i < resultEntries.length   1; i  ) {
        row = document.getElementById('line_'   i) // This is what is returning null
        console.log(row)
        row.style.display = 'block';
      }
      hidden = false
    }
  }
});

CodePudding user response:

You overshoot your elements with the 1 in the for loops

If you need this 1 based (not recommended) it is

for (let i = 1; i <= resultEntries.length; i  ) 

Also I think you can simplify this. Here is my guess without seeing the HTML

const resultEntries = document.querySelectorAll('.result-row');
document.addEventListener("keypress", function(event) {
  if (event.key !== '`') return;
  resultEntries.forEach((res, i) => {
    let x = document.getElementById('root_cause_'   i)
    if (x) {
      let value = x.value;
      console.log('value'   value)
      document.getElementById('line_'   i).hidden = value === '';
    }
  })
});

CodePudding user response:

Answering to save people from spending more time on this:

The issue was that my loop was starting from 0 while the elements were starting from line_1, meaning I was later on trying to alter the style of a null element.

  • Related