digiwig digiwig - 1 month ago 4
jQuery Question

jQuery form select on change filter table

I have a form with four dropdowns, each with

X
amount of values listed;

Subject, Type, Month, Location

And then I have a table with multiple rows pulled from a database with the exact same column headers.

Subject, Type, Month, Location

Each row of data is different.

I want to build a filter system where the
$(select).change
function comes in, builds an array of values from all selected dropdowns, and then applys the jquery
hide/show
function wherever it corresponds. The table rows have classes assigned to them dynamically eg:

<tr class="subjectVal typeVal monthVal locationVal"><td>lorem ipsum</td>...</tr>


At the moment I have:

$("form select").change(function() {

var values = [];
$("form select").each(function() {
if ($(this).val() != "Please select...") {
values.push($(this).val());
}
});

$("table.events tr.row").each(function() {
tr = $(this);
$.each( values, function(index, item){
if (!$(tr).hasClass(item)) {
$(tr).hide();

} else {
$(tr).show();
}
});

});

});


But this if the value array contains more than one item, only that item is filtering the table. If I choose a subject, then choose a location, it will always show all of those locations regardless of the subject I have chosen.

Answer

So basically it should only show the row if all values match? If so then this code should work:

$("table.events tr.row").each(function() {
    var tr = $(this), show = true;
    $.each( values, function(index, item){
        if (!tr.hasClass(item)) {
            show = false;
        }
    });
    tr.toggle(show);
});