Multiple Javascript If / Else Statements not working, only last one is executing

First of all, your poor indentation of code made this question very difficult to read and troubleshoot. I had to not only recreate the solution, but I also had to fix your invalid HTML. All of that was necessary before I recognized your problem is simply this —

Your first IF condition does work….

if (document.getElementById('BSN').value === 'Yes') {
  document.getElementById('BSNQuestion').style.display = 'table-row';
  document.getElementById('NSG_Grad_Yr').style.display = 'block';
  document.getElementById('Est_NSG_School').style.display = 'block';
} else {
  document.getElementById('BSNQuestion').style.display = 'none';
  document.getElementById('NSG_Grad_Yr').style.display = 'none';
  document.getElementById('Est_NSG_School').style.display = 'none';
}

… but its effects are later reversed by this condition:

if (document.getElementById('BSN').value === 'Currently Enrolled') {
  document.getElementById('BSNQuestion').style.display = 'table-row';
  document.getElementById('NSG_Grad_Yr').style.display = 'block';
  document.getElementById('Est_NSG_School').style.display = 'block';

} else {
  document.getElementById('BSNQuestion').style.display = 'none';
  document.getElementById('NSG_Grad_Yr').style.display = 'none';
  document.getElementById('Est_NSG_School').style.display = 'none';
}

Suppose value == ‘Yes’ then you continue to check value == ‘Currently Enrolled’. Since value was not ‘Currently Enrolled’ (since we know it was ‘Yes’) you still trigger the else condition that hides the display (even though you want it to show for ‘Yes’).

To fix, do this:

var answer = document.getElementById('BSN').value;
if (answer === 'Yes' || answer === 'Currently Enrolled') {
  document.getElementById('BSNQuestion').style.display = 'table-row';
  document.getElementById('NSG_Grad_Yr').style.display = 'block';
  document.getElementById('Est_NSG_School').style.display = 'block';
} else {
  document.getElementById('BSNQuestion').style.display = 'none';
  document.getElementById('NSG_Grad_Yr').style.display = 'none';
  document.getElementById('Est_NSG_School').style.display = 'none';
} 

Fiddle >

Leave a Comment