Reputation:
I am preparing a html table with >100 different names, but I only want some rows to show up. So far I use a javascript to "hide" everything and then "show" for those I want to show in the table. Is there a way to make the script hide EVERYTHING by default, and then use "show" for those I want to appear in the final table?
Here is the code for a basic example with only 5 different names (John, Ida, Thor, Diana, Chris) where I want Diana and Christ to show.
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="jquery/jquery-1.12.2.js"></script>
<table id="subtable">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
</tr>
<tr>
<td>Ida</td>
</tr>
<tr>
<td>Thor</td>
</tr>
<tr>
<td>Diana</td>
</tr>
<tr>
<td>Chris</td>
</tr>
</table>
<script type="text/javascript">
$(document).ready( function() {
$('#subtable td:contains("John")').parents("tr").hide();
$('#subtable td:contains("Ida")').parents("tr").hide();
$('#subtable td:contains("Thor")').parents("tr").hide();
$('#subtable td:contains("Diana")').parents("tr").hide();
$('#subtable td:contains("Chris")').parents("tr").hide();
$('#subtable td:contains("Diana")').parents("tr").show();
$('#subtable td:contains("Chris")').parents("tr").show();
});
</script>
</html>
Upvotes: 0
Views: 120
Reputation: 65806
Is there a way to make the script hide EVERYTHING by default
This is easily done by applying a CSS class that hides content:
.hidden { display:none; }
to all the the rows:
$("tr").addClass("hidden");
and then use "show" for those I want to appear in the final table
The showing of the rows is done with JavaScript/JQuery to simply remove the .hidden
class from those elements with another class identifying them as ones to be shown.
<tr class="shown">
Here's an example:
$("tr").addClass("hidden"); // Hide all rows
$("button[type='button']").on("click", function(){
// Remove the hidden class from rows that have the "shown" class
$(".shown").removeClass("hidden");
});
/* Apply this class to elements that should be hidden */
.hidden { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="subtable">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr class="shown">
<td>John</td>
</tr>
<tr>
<td>Ida</td>
</tr>
<tr class="shown">
<td>Thor</td>
</tr>
<tr>
<td>Diana</td>
</tr>
<tr class="shown">
<td>Chris</td>
</tr>
</table>
<button type="button">Show Appropriate Rows</button>
Upvotes: 2