cgrouge cgrouge - 1 year ago 117
CSS Question

Javascript to find check and display corresponding div

I'm trying to create a function that finds all checked check boxes that start with a value and display the corresponding div that is hidden below.

I have an example started here:


In the example, if the first checkbox is checked, I want to show the response to that checkbox below. The same would happen for the second checkbox.

I was thinking I could try something like this:


Then change the css to
but that wasn't working

Answer Source

You can find all checked checkboxes, than iterate over them. Then for each of them you can find the related div, and show it.

To show it, I added the class visible, so that if response class has also class visible, you can see it, otherwise it's not visible.

Every times you click the button, the visible class is removed from every response div, so that you hide all the divs, before show the wanted divs.

function postResponse() {
.response:not(.visible) {
  display: none;
<script src=""></script>
  <label for="test1">Test1</label>
  <input type="checkbox" id="test1">
  <label for="test2">Test2</label>
  <input type="checkbox" id="test2">
  <div class="responseContainer">
    <div class="response" id="test1Response">
      Response for Test1
    <div class="response" id="test2Response">
      Response for Test2
    <button type="button" onclick="postResponse()">
      Post Data

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download