Reputation: 51
I have a table structure where the rows comes from a database like this:
@foreach (var item in Model)
...
<tr>
<td>Dataset1 <button id="@(item.Id)">Show more</button></td>
</tr>
<tr id="@(item.Id)">
<td>Data from Dataset1</td>
</tr>
<tr>
<td>Dataset1 <button id="1">Show more</button></td>
</tr>
<tr id="1">
<td>Data from Dataset1</td>
</tr>
<tr>
<td>Dataset4 <button id="4">Show more</button></td>
</tr>
<tr id="4">
<td>Data from Dataset4</td>
</tr>
<tr>
<td>Dataset5 <button id="5">Show more</button></td>
</tr>
<tr id="5">
<td>Data from Dataset5</td>
</tr>
<tr>
<td>Dataset6 <button id="6">Show more</button></td>
</tr>
<tr id="6">
<td>Data from Dataset6</td>
</tr>
Now I would like to show or hide the different lines with the corresponding button with jquery. But everything I've tried so far does not work. Is there even the possibility to pass an id?
<script>
$(document).ready(function () {
$("button").click(function () {
$("id").toggle();
});
});
</script>
Upvotes: 0
Views: 63
Reputation: 1074028
id
values must be unique in the document. You can't have the same id
on both a tr
and a button
.
The solution is: Don't use id
at all. Put a class on your buttons and use traversal to find the row to toggle. I'd probably also use a delegated handler on the table rather than per button.
$("#the-table").on("click", ".show-more", function() {
$(this).closest("tr").next().toggle();
});
<table id="the-table">
<tr>
<td>Dataset1 <button class="show-more">Show more</button></td>
</tr>
<tr style="display: none">
<td>Data from Dataset1</td>
</tr>
<tr>
<td>Dataset4 <button class="show-more">Show more</button></td>
</tr>
<tr style="display: none">
<td>Data from Dataset4</td>
</tr>
<tr>
<td>Dataset5 <button class="show-more">Show more</button></td>
</tr>
<tr style="display: none">
<td>Data from Dataset5</td>
</tr>
<tr>
<td>Dataset6 <button class="show-more">Show more</button></td>
</tr>
<tr style="display: none">
<td>Data from Dataset6</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
(You might also use a class for hiding/showing and toggleClass
rather than toggle
.)
Upvotes: 1