0

I have a button to toggle a class to hide and show when a button is clicked.

My problem is a toggle only works for one specific element. It wont work for multiple classes / or ID's. I have a @foreach loop that loops through blogs, and on click, I need the div to be hidden, but all those foreach loops generate the same ID.

This is what I have right now:

 <button class="btn btn-primary">Preview</button> <br />


@foreach($blog as $b)
  <div class="col-md-12" class="toggleButtonsFeatured">
    some text here....
  </div>
@endforeach


 <script>
        $( "button" ).click(function() {
            $(".toggleButtonsFeatured").toggleClass(); 
        });
 </script>   

How would I toggle all those dynamically produced div's at once?

David
  • 1,987
  • 5
  • 33
  • 65
  • 1
    Did you mean to use `.toggleClass()` instead of `.toggle()`? Could you please explain some more what the expected behavior is? – 4castle Jan 05 '17 at 18:41
  • I'll change it to IDs, and the behavior is whatever is inside that ID is hidden when that button is clicked – David Jan 05 '17 at 18:43
  • You can't give the same ID to multiple things in the HTML. IDs are expected to be unique, so it will only ever select one element. – 4castle Jan 05 '17 at 18:49
  • What about classes, how would I loop through each class and toggle whatever is inside? I'll update the question – David Jan 05 '17 at 18:53
  • Sorry, I mislead you about using `.toggleClass()` earlier because I didn't understand the question. Make sure to look up the documentation for the functions you're using. – 4castle Jan 05 '17 at 18:56

2 Answers2

2

Change the "id" to class and toggle by class. Jquery isn't able to change multiple elements with the same id. You should never have more than one element on a page with the same id.

<button class="btn btn-primary">Preview</button> <br />


@foreach($blog as $b)
  <div class="col-md-12 toggleButtonsFeatured">
    some text here....
  </div>
@endforeach


<script>
    $( "button" ).click(function() {
        $(".toggleButtonsFeatured").toggle(); 
    });
</script>   

Could also try putting your jquery code in a document ready function.

itwasmattgregg
  • 353
  • 2
  • 8
0

If these are dynamically generated, you may need to wrap it in a static element first and attach the click listener to that element.

<button class="btn btn-primary">Preview</button> <br />

<div id="wrapper">
@foreach($blog as $b)
  <div class="col-md-12 toggleButtonsFeatured">
    some text here....
  </div>
@endforeach
</div>


<script>
    $("#wrapper").on("click", ".toggleButtonsFeatured", function() {
        $(".toggleButtonsFeatured").toggle(); 
    });
</script>  
Loaf
  • 3,011
  • 2
  • 15
  • 25