I have a button on a page that I want to only show rows that have a certain class ( target-class
in my example) within them. If you press the button again, then all rows are shown.
I'm not sure how to check if target-class
is within <tr class="show-hide-this-one">
<button id="btn-toggle_target" type="button">Show Targets Only</button>
<table>
<tbody>
{% for item in first_list %}
<tr class="show-hide-this-one">
<td> {{ item.title }} </td>
<td>
<table><tbody>
{% for subitem in item.sublist %}
<tr>
<td>
{{ subitem.value }}
{% if value == 0 %}
<span class="target-class"> Looking for this one </span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody></table>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<script type="text/javascript">
function toggleTarget() {
$btnToggle = $("#btn-toggle_target")
var showTargetOnly = $btnToggle.hasClass("target-only")
if (showTargetOnly) {
$btnToggle.html("Show Targets Only").removeClass("target-only");
$().show();
}
else {
$btnToggle.html("Show All Records").addClass("target-only");
$().hide();
}
}
(function () {
$("#btn-toggle_target").on('click', function() {
toggleTarget();
});
}());
</script>
it was not so easy because you dont have class or id but with a little loop its ok:
$("#btn-toggle_target").on('click', function() { toggleTarget(); }); function toggleTarget() { var showTargetOnly = $("#btn-toggle_target").hasClass("target-only"); if (showTargetOnly) { $("#btn-toggle_target").html("Show Targets Only").removeClass("target-only"); $(".show-hide-this-one table tr").show(); } else { $("#btn-toggle_target").html("Show All Records").addClass("target-only"); $(".show-hide-this-one table td").each(function(){ if($(this).find(".target-class").length == 0) $(this).closest("tr").hide(); }) //this loop coul be replaced by //$(".show-hide-this-one table td:not(:has(.target-class))").closest("tr").hide(); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="btn-toggle_target" type="button">Show Targets Only</button> <table> <tbody> <tr class="show-hide-this-one"> <td> Item 1 </td> <td> <table><tbody> <tr> <td> 0 <span class="target-class"> Looking for this one </span> </td> </tr> <tr> <td> 1 </td> </tr> <tr> <td> 3 </td> </tr> </tbody></table> </td> </tr> <tr class="show-hide-this-one"> <td> Item 2 </td> <td> <table><tbody> <tr> <td> 4 </td> </tr> </tbody></table> </td> </tr> </tbody> </table>
i think, you could replace this loop:
$(".show-hide-this-one table td").each(function(){
if($(this).find(".target-class").length == 0) $(this).closest("tr").hide();
})
by
$(".show-hide-this-one table td:not(:has(.target-class))").closest("tr").hide();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.