I have a series of a series of rows and checkboxes to filter them:
- &l
$("table tr").hide();
$("input[id^='type-']").each(function() {
element = $(this);
$("table tr").each(function() {
if($(this).hasClass(element.id.replace('type-','')) {
if(element.is(":checked") {
element.show();
}
}
});
}).change();
jQuery has created this function for you! It's called .filter(), and it takes either a selector string, a function, a raw DOM element, or a jQuery object. In your case, I'd pass it a selector string. We can make use of jQuery's :has() selector, which takes a selector and returns the matched elements. So, if you wanted to select all rows (li
elements) that contain checked checkboxes, you could do it like this:
$("li").filter(":has(input:checked)");
Or, we could eliminate our call to filter()
and simply pass the entire selector to $()
:
$("li:has(input:checked)");
That will return all li
elements that contain any checked checkboxes anywhere among it's descendants, not just it's direct children.
And putting it in the context of your .change()
handler:
I'm assuming you want to show tr
elements that have the same type as the li
elements that contain checked checkboxes, and hide any tr
elements that don't. So, we'll make use of the .toggle() function, which toggles the visibility of elements:
$(function(){
$("input[id^='type-']").change(function() {
$("."+this.id.replace('type-','')).toggle(this.checked);
// show any tr elements that have the class relating to the type of the inputs that contain checked checkboxes...
$("li:has(input:checked)").each(function() {
$("tr" + "." + this.id.replace(/type-/, "")).toggle();
});
}).change();
});
Modify the function to get a selector for all the checked check boxes.
$(function(){
var $checkboxes = $("input[id^='type-']");
$checkboxes.change(function() {
var selector = '';
$checkboxes.filter(':checked').each(function(){ // checked
selector += '.' + this.id.replace('type-','') + ', ';
// builds a selector like '.A, .B, .C, '
});
selector = selector.substring(0, selector.length - 2); // remove trailing ', '
// tr selector
$('table tr').hide() // hide all rows
.filter(selector).show(); // reduce set to matched and show
}).change();
});
EDIT: see jsfiddle