I am working on a Table Row filtering script.
Initially, the all table rows are visible, but after manipulating some dropdowns / forms the filter criteria dictate which rows are going to be visible and which not. Example:
var jobs = [{
id: 0,
company: "Google",
location: "Zurich"
}, {
id: 1,
company: "Facebook",
location: "Ireland"
}];
// this function isn't run in this example for reasons of brevity. it's to show how the jobs array is generated
const filterRow = function (data, filters) {
let filtersEnabled = Object.keys(filters).filter(element => filters[element].length !== 0);
return data.filter(row => {
return filtersEnabled.every(k => {
return filters[k].indexOf(row[k]) !== -1
})
})
}
let $tableRows = $('table tbody tr');
const updateDisplay = function() {
// that's not ideal
$tableRows.addClass('hidden')
jobs.forEach((row) => {
$(`[data-id="${row.id}"]`).removeClass('hidden')
})
}
$('.js-filter').on('click', () => updateDisplay())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button class="js-filter">filter table now</button>
<table class="table table-bordered">
<tbody>
<tr data-company="google" data-id="0" data-loation="zurich">
<td>Google</td>
<td>Zurich</td>
<td>0</td>
</tr>
<tr data-company="facebook" data-id="1" data-loation="ireland">
<td>Facebook</td>
<td>Ireland</td>
<td>1</td>
</tr>
<tr data-company="microsoft" data-id="2" data-loation="california">
<td>microsoft</td>
<td>California</td>
<td>2</td>
</tr>
</tbody>
</table>
The jobs array determines which rows are going to be visible. (so in this particular case, only rows with id 0 and 1 are going to be visible.
Given that the jobs array is changing programmatically, I would like a jQuery (or other) way to directly hide the rows with ID not present in the array (thus being able to use animate.css to fade rows out etc.
What I currently do is
- hiding all rows,
- then showing the ones in the array. That's rather a workaround and it complicates my transitions/animations.