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 i
from 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
- You should inverse your use of ' and "... using '...' to delimit attributes isn't valid HTML5 (you need
<div style="..."></div>
, not<div style='...'></div>
) - You see
foo(2)
everywhere because that's the last valuei
had. Your onclick works, but is fetching the last value thati
had, instead of hardcoding the value ofi
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
Convert HTML Table to Array in JavaScript
Html/Javascript: Simple Form Validation on Submit
React: Why Child Component Doesn't Update When Prop Changes
Change the Content of a Div Based on Selection from Dropdown Menu
Create a Simple 10 Second Countdown
How to Swipe Top Down Jquery Mobile
Adding Rows Dynamically with Jquery
D3Js Take Data from an Array Instead of a File
Print a Div Using JavaScript in Angularjs Single Page Application
How to Get a Value of a <Span> Using Jquery
How to Bind the HTML <Title> Content in Vuejs
Session Only Cookies with JavaScript
How to Submit a Form When the Return Key Is Pressed
How to Use Any HTML5 Fanciness to Export Local Storage to Excel
How to Convert Raw JavaScript Object to a Dictionary