Currently, I am facing a challenge in creating filters for a dynamically generated table. I have implemented checkboxes as part of my solution, but I seem to be stuck at this point.
Despite conducting extensive research, I have been unable to find a suitable resolution to my problem.
My main objective is to filter the data displayed in the table based on the selected checkboxes. Unfortunately, I am struggling with the concept of connecting these checkboxes to the corresponding table rows that need to be filtered based on user input.
I attempted using event.target.getAttribute('data-filter'), however, I encountered difficulties filtering the array to align with the event triggered by the checkbox selection.
Is there a way to achieve this functionality using only pure JavaScript?
Below is the snippet of code I've been working on:
let array= [
{
"name": "John",
"surname": "XYZ",
"department": "IT"
},
{
"name": "John",
"surname": "XYZ",
"department": "accountancy"
},
]
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}
let table = document.querySelector("table");
let data = Object.keys(array[0]);
generateTable(table, array);
generateTableHead(table, data);
// FILTER: checkboxes
const getDepartments = array.map(function (element) {
return [element.department].join('');
});
let departmentFilters = [...new Set(getDepartments)];
let createFilters = function () {
box = document.querySelector('#filterType');
box.innerHTML = departmentFilters.map(function (department) {
let checkboxes = '<label>' +
'<input type="checkbox" data-filter="' + department + '" checked>' + department +
'</label>';
return checkboxes;
}).join('');
};