Reputation: 151
I have a table which I would like to have a button onClick which will run the toggle() function
at the moment, I can hide the M values but not bring them back,
lets say for example this is how the table looked
+-------+--------+
| Name | Gender |
+-------+--------+
| James | M |
+-------+--------+
| Gemma | F |
+-------+--------+
| John | F |
+-------+--------+
heres the toggle function
function toggle() {
var searchString = 'M';
$("#t01 tr td:contains('" + searchString + "')").each(function() {
if ($(this).text() == searchString) {
$(this).parent().hide();
}
});
}
Upvotes: 1
Views: 1637
Reputation: 15154
It would be easier to go from the tr
and inspect inside like below:-
function toggle(gender) {
$('#t01 tbody tr').each(function() {
$(this).toggle($('td:eq(1):contains(' + gender + ')', this).length > 0);
})
}
function show() {
$('#t01 tbody tr').show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="t01">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>M</td>
</tr>
<tr>
<td>Gemma</td>
<td>F</td>
</tr>
<tr>
<td>John</td>
<td>F</td>
</tr>
</tbody>
</table>
<button onclick="toggle('M')">Male</button>
<button onclick="toggle('F')">Female</button>
<button onclick="show()">All</button>
Upvotes: 2
Reputation: 31
If your code is working properly for hiding the row then you can simply replace hide() with toggle() to show/hide keeping the rest same, or you can simplify the code as told by BG101.
function toggle() {
var searchString = 'M';
$("#t01 tr td:contains('" + searchString + "')").each(function() {
if ($(this).text() == searchString) {
$(this).parent().toggle();
}
});
}
Upvotes: 1