Skip to content Skip to sidebar Skip to footer

Creating Unique Id Buttons In A Javascript Loop

I need to create a table populated with buttons. Each button must have a unique id in order to edit values in it's row. I set an alert displaying button's id on click, but all crea

Solution 1:

Change your client handler to refer to the actual button that was clicked. Change from this:

newButton.onclick = function(){
    alert("Button Id: " + newButton.id);
}

to this:

newButton.addEventListener("click", function(e) {
    alert("Button Id: " + this.id);
});

The variable newButton is used over and over again in your for loop so by the time any of your onclick handlers actually run, all the buttons have been created and newButton will contain the last value it ever had.

Instead, you can use this to refer to the element that was clicked on so this.id will the id value of the button that was clicked.

Note: I also switch to using .addEventListener() which also passes an event data structure to the event handler (shown as the e argument in my code). This is a generally better way to register event listeners as it allows multiple listeners and gives you automatic access to other info about the event that occurred.

Post a Comment for "Creating Unique Id Buttons In A Javascript Loop"