I'm making a dynamic button for each for in a table to delete. I make the button id have the key to the row so I can query it on click to know which one to delete. Since I'm assigning all buttons the same function I need to pass the button that was clicked to the event handler so I can query the id from inside the event handler.
When hardcoding I'd just pass 'this' to the event handler. How do I do this when making a dynamic button?
Right now I have:
{
var cell0 = row.insertCell(0);
var btn = document.createElement("input");
btn.type = "button";
btn.id = "btnHistorySelect_" + roundHdr[i].id; // append the id to the name so we can get it when select button is clicked so we know what round to select as current
btn.value = "Set Current";
btn.onclick = btnHistorySelect;
cell0.appendChild(btn);
}
function btnHistorySelect() {
}
The event handler gets called, but I have no idea what button made the click.
You can use the this.id or event.target.id attribute to get the id of the button that initiated the event.
function btnHistorySelect(event) {
var id = this.id;
or
// var elem = event.target;
// var id = elem.id
}
Because you are assigning the function reference , the this inside the function corresponds to the current element is question.
function btnHistorySelect(event) {
alert(event.target); // Will alert the actual element clicked.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With