Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript dynamic button click event

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.

like image 707
user441521 Avatar asked Feb 04 '26 10:02

user441521


2 Answers

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.

like image 164
Sushanth -- Avatar answered Feb 06 '26 23:02

Sushanth --


function btnHistorySelect(event) {
   alert(event.target); // Will alert the actual element clicked.
}
like image 30
Jim Blackler Avatar answered Feb 06 '26 22:02

Jim Blackler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!