Reputation: 5178
I have an html.erb
file where I'm creating a new row as I iterate over a collection. I need to be able to dynamically create an id
per row, and then be able to specify that id
in my .js
file so that I can show/hide some of its contents when clicked.
#foo.html.erb file
<table>
<thead>
<tr>
<th> Group Name </th>
<th> </th>
<th> Count </th>
</tr>
</thead>
<tbody>
<% @groups.each do |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 be hidden. If the row this data belongs to is clicked, then show it. If clicked again, then hide it.
</tr>
<% end %>
</tbody>
</table>
And then I need to be able to show/hide that group's count
when clicked, but I don't know how to find an id that was dynamically created:
#app/assets/javascripts/test.js
$(document).ready(function(){
$("#dynamic_group_id").on(“click”, function(e){ #somehow be able to specify the dynamically created id
#show/hide contents
});
});
Upvotes: 1
Views: 118
Reputation: 102001
You are abusing element IDs. Use IDs for truly unique identifiers.
For everything else there are other selectors - the most commonly used are 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>
Upvotes: 1