I currently have sort buttons for each column of a table in my application, and when I click on one of the sort buttons I want the ID of that button to be passed into the function so that the correct column is sorted. In my HTML I simply have a table as such...
<table id="table"></table>
I then have a few functions that populate the table with all needed rows from the database. For the function that creates the heading row, it will also append a sort button to the end of each cell in that row. I create the sort button through this following method...
const createSortBtn = item => {
let btn = document.createElement("button");
btn.innerHTML = '▼';
btn.id = item;
btn.addEventListener("click", sortTable);
return btn;
}
The variable item is the ID I wish to give the button that is being created, the innerHTML is just a down triangle, and then I also add the onclick function. This onclick function goes as so...
const sortTable = () => {
let order, index = this.id;
if (document.getElementById(index).innerHTML === '▼') order = "ASC";
else order = "DESC";
window.sessionStorage.setItem("order", order);
window.sessionStorage.setItem("index", index);
makeSearch();
}
Most of the function is not too relevant to my question except for the this.id part. From what I have been able to find so far this seems to be the primary method of acquiring the ID of an onclick button (even in strict mode if what I believe is true). However when it is called in the function it is undefined.
I had been thinking that perhaps I could change the code that when I add the onclick function to the sort button it would go like so...
const createSortBtn = item => {
let btn = document.createElement("button");
btn.innerHTML = '▼';
btn.id = item;
btn.addEventListener("click", sortTable(item));
return btn;
}
...but that seems to call the function immediately which is not the behaviour I wish for.
I have seen that jQuery seems to have quite a few methods of doing this but I am hoping to stick to native JavaScript if possible. Thanks for all help.