0
votes

I have a few checkboxes:

<input type="checkbox" name="filterby" id="type" value="type" onchange="showFilter();" />Type<br>
<input type="checkbox" name="filterby" id="conseq" value="conseq" onchange="showFilter();" />Consequence<br>
<input type="checkbox" name="filterby" id="group" value="group" onchange="showFilter();" />Group<br>
<input type="checkbox" name="filterby" id="sample" value="sample" onchange="showFilter();" />Sample<br>

and a div for each one, that I want to show and hide when clicked. This is my function:

function showFilter() {
  var filterby = ["type", "conseq", "group", "sample"];

  for (var i = 0; i < filterby.length; i++) {
    var option_on = document.getElementById(filterby[i]).checked;
    var filterby_list = filterby[i] + "_list";

    if (option_on == true) {
      document.getElementById(filterby_list).style.display = "block";
    }
    else {
      document.getElementById(filterby_list).style.display = "none";
    }
  }
}

I have been looking at it for hours and can't figure out why it doesn't work. If I delete the if-else statement, it runs through, if not, it works for the first checkbox and not the others, it stops when looping over the second. Where is my error?

Thank you.

1
What is filterby_list? - Joeri van Veen
What happens if you step through in a debugger? My guess is that the if statement is crashing and that stops the script. - Raymond Chen
There should be an error in the console, pointing out which element is missing - Bergi

1 Answers

3
votes

If I add divs with the correct ID's your script expects, your code works. So your problem is not with the code shown. Does your HTML contain the correct id values on the divs you want to show and hide?

function showFilter() {
  var filterby = ["type", "conseq", "group", "sample"];

  for (var i = 0; i < filterby.length; i++) {
    var option_on = document.getElementById(filterby[i]).checked;
    var filterby_list = filterby[i] + "_list";

    if (option_on == true) {
      document.getElementById(filterby_list).style.display = "block";
    }
    else {
      document.getElementById(filterby_list).style.display = "none";
    }
  }
}
<input type="checkbox" name="filterby" id="type" value="type" onchange="showFilter();" />Type<br>
<input type="checkbox" name="filterby" id="conseq" value="conseq" onchange="showFilter();" />Consequence<br>
<input type="checkbox" name="filterby" id="group" value="group" onchange="showFilter();" />Group<br>
<input type="checkbox" name="filterby" id="sample" value="sample" onchange="showFilter();" />Sample<br>

<div id="type_list">type</div>
<div id="conseq_list">conseq</div>
<div id="group_list">group</div>
<div id="sample_list">sample</div>