简体   繁体   中英

Javascript to show/hide <c:forEach> div element of JSTL

I have an JSTL for each tag as follows.

  <c:forEach items="${schedule}" var="period">
               <td>
                   <div id="friends">    
                     ${period.getFriends()}
                </div>
                 </td>
     </c:forEach>

I want to implement a button that on click will hide or show all these blocks. So far all the button does is hide or show the first element of the block. I dont know why it doesn't iterate through all the block.

<button onclick="myFunction()" class="btn btn-success btn-xs">With friend</button>
                        <button class="btn btn-danger btn-xs">Without friend</button>
                        <script>
                            function myFunction() {
                                var div = document.getElementById('friends');
                                div.innerHTML = "AFJASFAS";
                            }
                        </script>

As you can see I didn't really implement the show and hide for the buttons yet. I just tests it by adding in extra text however, this text is only added to the first div. How can i make it so it applies to all the elements?

That's obvious, because you are using one ID for all blocks! ID must be unique in the html page, but you have many <div id="friends"> . When you have some elements with same ID, javascript select first element. Solution is to use Class instead of ID:

<c:forEach items="${schedule}" var="period">
           <td>
               <div class="friends">    
                 ${period.getFriends()}
            </div>
             </td>
 </c:forEach>

 function myFunction() {
      var div = document.getElementsByClassName("friends");
      div.innerHTML = "AFJASFAS";
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM