0

I'm currently trying to figure out a way to sort a HTML table's column when you click on the relevant header. What's making it challenging is that the table I've made is generated with pure JS, and the only way I've managed to "sort of" capture click events is during the loop when I generate the table headers using onclick.

Here is the code:

headerArray.forEach(function(heading) {
    let el = document.createElement('th');
    el.onclick = function(e) { 
        console.log(e.target);
    };
    el.appendChild(document.createTextNode(heading));
    header.appendChild(el);
});

As you can see, all I'm doing at the moment is outputting to the console. I've tried adding event listeners and the clicks weren't registering. I'm trying to do this in pure JS. Is there an effective way to achieve this even when creating the table dynamically?

My complete function for creating the table is as follows (just for reference the data is loaded in from a JSON object):

function makeTable(data) {

    let table = document.createElement('table');
    table.id = 'dataTable';

    let thead = document.createElement('thead');
    table.appendChild(thead);

    let tbody = document.createElement('tbody');
    table.appendChild(tbody);

    let header = document.createElement('tr');

    let headerArray = ['Date', 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7'];
    let jsonKeys = ['date', 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'];

    headerArray.forEach(function(heading) {
        let el = document.createElement('th');
        el.onclick = function(e) { 
            console.log(e.target);
        };
        el.appendChild(document.createTextNode(heading));
        header.appendChild(el);
    });

    thead.appendChild(header);

    for (let i = 0; i < Object.keys(data).length; i++) {

        let tr = document.createElement('tr');
        for (let j = 0; j < jsonKeys.length; j++) {
            let el = document.createElement('td');
            el.appendChild(document.createTextNode((j == 0) ? formatDate(Object.keys(data)[i].split('-')) : data[Object.keys(data)[i]][jsonKeys[j]]));
            tr.appendChild(el);
        }

        tbody.appendChild(tr);

    }

    document.body.appendChild(table);
}

What would be the best way for me to accomplish this?

Matt Kent
  • 1,145
  • 1
  • 11
  • 26
  • `What would be the best way for me` to use [DataTables](https://datatables.net/) – Sysix Feb 02 '18 at 23:43
  • See this post: [Sort Table by click in header tag regardless of it is numeric, alphabetical or date](https://stackoverflow.com/questions/46923526/sort-table-by-click-in-header-tag-regardless-of-it-is-numeric-alphabetical-or-d). – Danny Fardy Jhonston Bermúdez Feb 02 '18 at 23:46
  • @Sysix Thank you, sorry if I didn't make it clear but ideally if this could be achieved with pure JS then that would be the ideal solution – Matt Kent Feb 02 '18 at 23:46

0 Answers0