cgrouge cgrouge - 17 days ago 7
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:

Demo
: https://jsfiddle.net/3wf34nbf/3/

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:

.find("div[id^=$(this)]")


Then change the css to
display:block
but that wasn't working

Answer

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").removeClass('visible');
  $("input[type=checkbox]:checked").each(function(){
    $("#"+$(this).attr('id')+"Response").addClass('visible');    
  });
}
.response:not(.visible) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <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>
    <div class="response" id="test2Response">
      Response for Test2
    </div>
  </div>
  <div>
    <button type="button" onclick="postResponse()">
      Post Data
    </button>
  </div>
</form>

Comments