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.
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.
Share Improve this question asked Nov 28, 2012 at 20:32 user441521user441521 6,99826 gold badges98 silver badges167 bronze badges4 Answers
Reset to default 4You 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.
}
You don't need to know or assign an id if you are using this
HTML input button element is available inside btnHistorySelect
function through this
variable.