javascript - Create unique id per iteration, then specify behavior when clicked -
i have html.erb
file i'm creating new row iterate on collection. need able dynamically create id
per row, , able specify id
in .js
file can show/hide of contents when clicked.
#foo.html.erb file <table> <thead> <tr> <th> group name </th> <th> </th> <th> count </th> </tr> </thead> <tbody> <% @groups.each |group_name, count_for_group| %> <tr id="unique_id"> #create unique id here <td> <%= group_name %> </td> <td> </td> <td> <%= count_for_group %> </td> #this should hidden. if row data belongs clicked, show it. if clicked again, hide it. </tr> <% end %> </tbody> </table>
and need able show/hide group's count
when clicked, don't know how find id dynamically created:
#app/assets/javascripts/test.js $(document).ready(function(){ $("#dynamic_group_id").on(“click”, function(e){ #somehow able specify dynamically created id #show/hide contents }); });
you abusing element ids. use ids unique identifiers.
for else there other selectors - commonly used classes.
$(".group").on('click', function() { $(this).find('.hide-me').toggle(); }); console.log($(".group"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <tr> <th>group name</th> <th> </th> <th>count</th> </tr> </thead> <tbody> <tr class="group"> <td>the beatles</td> <td></td> <td class="hide-me">4</td> </tr> <tr class="group"> <td>the rolling stones</td> <td></td> <td class="hide-me">4</td> </tr> </tbody> </table>
Comments
Post a Comment