jebmarcus jebmarcus - 3 months ago 41
HTML Question

Show and hide multiple divs with same class name not working

I want to show / hide an infinite number of divs all with the same class name. I use JQuery for this. See my jsfiddle: http://jsfiddle.net/1g2hw6hh/2/

I tried to use the next selector in JQuery

$(document).ready(function() {
$(".jsonInfo").hide(); // it's obvious
$(".showJSON").click(function() { // on click...

$(".jsonInfo")
.hide() // ...hide all other previus opened elements...
.eq($(this).index('.showJSON')) // ... select right one by index of clicked .showJSON element...
.toggle(); // and show/hide it
});
});


How do I fix this and get the divs to show/hide independently?

Answer

.next() pick next sibling element which have ".jsonInfo" class. Because your next sibilings are only buttons and div's with ".row" class, you need to use something like this:

$(document).ready(function() {
  $("div.jsonInfo").hide(); // it's obvious
  $("button.showJSON").click(function() {  // on click...
    
    $("div.jsonInfo")
      .hide()  // ...hide all other previus opened elements...
      .eq($(this).index('.showJSON')) // ... select right one by index of clicked .showJSON element...
       .toggle(); // and show/hide it
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="showJSON">Show JSON 1</button>
<button class="showJSON">Show JSON 2</button>
<button class="showJSON">Show JSON 3</button>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 1</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 2</h6>
  </div>
</div>

<div class="row">
  <div class="jsonInfo">
    <h6>JSON 3</h6>
  </div>
</div>

But you need to remember, you need to have the same amount of button.showJSON and div.jsonInfo in the same order.