Reputation: 803
I have a table where each visible row has a row beneath it whose visibility can be toggled by pressing a button. A live demo of this can be found here.
I'm really new to using jQuery and the problem I'm encountering is probably a simple fix to be honest. First of all, I want the togglable rows to be hidden by default and only shown when the button is clicked (now they show when the page is loaded). How can I do this?
To hide the rows I have the following:
$(document).ready(function(){
$("#button1").click(function(){
$(".trhideclass1").toggle();
});
});
$(document).ready(function(){
$("#button2").click(function(){
$(".trhideclass2").toggle();
});
});
I don't want to have to create a function for every button separately, so what is a better way to do this? My idea was to give a <button>
and <tr>
the same id
and somehow make the button only toggle stuff with the same id
, is this possible?
Upvotes: 0
Views: 360
Reputation: 4584
You can set default hide in css
.trhideclass1,.trhideclass2{
display : none;
}
For more easy to handle you should change your button id only as number
HTML
<button id="1" class="btn btn-primary">Click me</button>
<button id="2" class="btn btn-primary">Click me</button>
JS
$(document).ready(function(){
$(".btn").click(function(){
current = $(this).attr('id');
$('.trhideclass'+current).toggle();
});
});
Upvotes: 0
Reputation: 144689
You can add a class to the buttons (like btn-toggle
) and then traverse the DOM for getting the target element:
$(".btn-toggle").click(function() {
$(this).closest('tr').next('tr').toggle();
});
The values passed to the .closest
and .next
methods can be any valid selector. For understanding how these methods work you can refer to the jQuery documentations.
https://jsfiddle.net/mc1dkq6a/
Upvotes: 1