lundi 13 mai 2019

multiple filter by checkboxes - pure JS

I would like to create filters to the table. This table is generated from array. I've created checkboxes and now I'm stuck.

I've searched a lot, but I can not find a solution.

I want to filter the table data according to the generated check boxes, but I have no idea how to connect it all together. I do not know exactly how to collect objects from the table, which will match the value of the checkbox so that it filters the rows of the table after deselecting a given type.

I tried with event.target.getAttribute('data-filter') but there I have problem to filter array to match event.

Is any possibility to make someting like this just in pure javascript?

here my code:

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('');
};




Aucun commentaire:

Enregistrer un commentaire