Reputation: 784
I have implemented my version of this example (using Vapor Swift & Leaf) and it works fine: Simple example of collapsible rows in HTML/CSS/JS
However, I want all of the collapsible rows to start off hidden by default. I don't know JS very well but I don't think modifying this would help:
$(document).ready(function() {
$('[data-toggle="toggle"]').change(function(){
$(this).parents().next('.hide').toggle();
});
});
Do I need to make a different JS script and if so how will it find the correct rows to hide (and how to hide them)?
Upvotes: 1
Views: 722
Reputation: 6735
Since you are using the jQuery library, you can use a jQuery selector to select the elements you want to hide, and hide them on document load:
It looks like the rows that you want to toggle between hidden/shown all have the .hide
class. So you can use that as the selector:
$('.hide').toggle(); // hide rows initially
Run the snippet below to see how this works. Initially, the rows are hidden. If you click "Accounting" or "Management" the rows will expand.
$(document).ready(function() {
$('.hide').toggle(); // hide rows initially
$('[data-toggle="toggle"]').change(function() {
$(this).parents().next('.hide').toggle();
});
});
table {
width: 750px;
border-collapse: collapse;
margin: 50px auto;
}
th {
background: #3498db;
color: white;
font-weight: bold;
}
td,
th {
padding: 10px;
border: 1px solid #ccc;
text-align: left;
font-size: 18px;
}
.labels tr td {
background-color: #2cc16a;
font-weight: bold;
color: #fff;
}
.label tr td label {
display: block;
}
[data-toggle="toggle"] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Regian</th>
<th>Q1 2010</th>
<th>Q2 2010</th>
<th>Q3 2010</th>
<th>Q4 2010</th>
</tr>
</thead>
<tbody>
<tbody class="labels">
<tr>
<td colspan="5">
<label for="accounting">Accounting</label>
<input type="checkbox" name="accounting" id="accounting" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Australia</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
<tr>
<td>Central America</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
</tbody>
<tbody class="labels">
<tr>
<td colspan="5">
<label for="management">Management</label>
<input type="checkbox" name="management" id="management" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Australia</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
<tr>
<td>Central America</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
<tr>
<td>Europe</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
<tr>
<td>Middle East</td>
<td>$7,685.00</td>
<td>$3,544.00</td>
<td>$5,834.00</td>
<td>$10,583.00</td>
</tr>
</tbody>
</tbody>
</table>
Upvotes: 2