JavaScript - Dynamically Assign Onclick Event in the Loop

Javascript - Dynamically assign onclick event in the loop

You'll have to do something like this:

btnShow.onclick = (function(opt) {
return function() {
showParam(opt);
};
})(arrOptions[i]);

how to assign onclick events to dynamically-created buttons using javascript

Actually you have an issue with your code, because once you create a button, inject it in the DOM and attach an event, then the next iteration of your loop is simply removing it and creating a new instance of the button (with same id).

To fix it, you should not modifying the whole HTML but rather append child dynamically:
Initial code:

linksButtonsDiv.innerHTML = currentHTML + 
`<button type="button" id="${currentLink.rel}">${currentLink.rel}</button>`

New Code:

let button= document.createElement("button");
button.setAttribute('id', currentLink.rel);
button.innerHTML = currentLink.rel;
linksButtonsDiv.parentNode.appendChild(button);
function onClick() {
console.log("it workded");
}
button.addEventListener("click", onClick, false);

PS: It's a detail but this is not the most efficient way to do, it's better to push all your buttons at once in the DOM and then attach events.

Set onclick method for an element in a loop using local variables without having it activate immediately

You'll want to reference this in the function you call when the cell is clicked. It refers to the cell's element.

So, your onclick function will become this:

cell.onclick = function() { changeCellColor(this) };

More examples here

Javascript dynamically assign onclick event with parameter in html

You just need to remove ifrom the Javascript String:

for (var i = 0; i < 2; i++) {
if (i == 1) {
document.write(" <tr class='noBorder' onclick='foo(" + i + ")' >");
}
if (i == 0) {
document.write(" <tr class='noBorder' onclick='foo(" + i + ")' >");
}
}

2 Notes

  1. You should inverse your use of ' and "... using '...' to delimit attributes isn't valid HTML5 (you need <div style="..."></div>, not <div style='...'></div>)
  2. You see foo(2) everywhere because that's the last value i had. Your onclick works, but is fetching the last value that i had, instead of hardcoding the value of i when HTML was rendered.

Dynamically adding div's and setting onclick value in JavaScript for loop

Classic JS gotcha. Do this:

document.getElementById('Scene'+i).onclick = ((id) => () =>addScene(Scenes.PanoSet[id]))(i);

You need to bind in the value of i, rather than a reference. The handler code doesn't get evaluated until it gets executed, so the value of i at that time will be the value it has when the loop has completed.

Doing it using an IIFE (immediately-invoked function expression) creates a context with the correct static value of i bound into the scope of the handler that it returns.

dynamically making onClick event?

You need to break the closure with message_id:

newdiv[i].onclick = (function(id) {
return function() {expandThis(id) };
}(message_id));

There are a million questions like this one, e.g. Do while javascript Problem.

JavaScript Dynamic Button OnClick Event Only Aplies To Last Button Created

I think the issue is that var is not scoped to the for loop so when you create deleteButton the deleteButton variable is only created once, gets assigned to in each iteration of the loop and that one variable is what gets used by the onclick function. If you use let, each iteration of the loop will have its own deleteButton variable.

const table = document.getElementById('table');

for (let x = 0; x < 5; x++) {
let row = table.insertRow(x);
row.id = String(x);

let cell4 = document.createElement('td');

let deleteButton = document.createElement('button'); // Change var to let
deleteButton.innerHTML = 'Delete';
deleteButton.type = "button";
deleteButton.className = "deleteButton";

deleteButton.onclick = function() {

let rowID = deleteButton.closest("tr")?.id;

console.log('rowID', rowID);
}

cell4.append(deleteButton);

row.append(cell4);

table.append(row);
}
<table id="table"></table>


Related Topics



Leave a reply



Submit