Creating Dynamic button with click event in JavaScript
Wow you're close. Edits in comments:
function add(type) { //Create an input type dynamically. var element = document.createElement("input"); //Assign different attributes to the element. element.type = type; element.value = type; // Really? You want the default value to be the type string? element.name = type; // And the name too? element.onclick = function() { // Note this is a function alert("blabla"); };
var foo = document.getElementById("fooBar"); //Append the element in page (in span). foo.appendChild(element);}document.getElementById("btnAdd").onclick = function() { add("text");};
<input type="button" id="btnAdd" value="Add Text Field"><p id="fooBar">Fields:</p>
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>
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.
Javascript: onclick for dynamically created button
Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()
You need to bind on a static element that exists when the code .on()
is executing. Use event delegation:
$('#divCards').on('click', '.btn-success-cart', function(event){
event.preventDefault();
var _id = Number( $(this).attr("data-id") );
var _nome = $(this).attr("data-nome");
var _descricao = $(this).attr("data-descricao");
var _preco = Number( $(this).attr("data-preco") );
console.log("Item add");
addItem(_id, _nome, _descricao, _preco, 1);
updateCart();
});
How to give Onclick function to dynamic created button (Number of button will change every time)
Try this:
<button type="button" class="mybtn" id='+i+'>'+i+'</button>';
the button have a common class mybtn
and with incremented id
value in it.
And you can assign event listener to it like:
$(document).on('click', '.mybtn', function(){
alert( $(this).attr('id') );
// Will give the id value for the clicked button
});
Click event for dynamically created button
Add event when you create elements using addEventListener()
:
...
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton" +i);
button.addEventListener("click", clickEventFunction, false);
...
Hope this helps.
function makeHTMLMatchesTable(array) { var table = document.createElement('table'); table.setAttribute("border", 1);
for (var i = 0; i < array.length; i++) { var row = document.createElement('tr'); var cell = document.createElement('td'); cell.textContent = array[i]; row.appendChild(cell); cell = document.createElement('td'); var button = document.createElement('button'); button.setAttribute("id", "unMatchButton" + i); button.textContent = "Delete";
//click Event button.addEventListener("click", delete_row, false); cell.appendChild(button); row.appendChild(cell); table.appendChild(row); }
return table;}
function delete_row() { this.parentNode.parentNode.remove();}
document.body.appendChild(makeHTMLMatchesTable(['Cell 1','Cell 2','Cell 3','Cell 4']));
OnClick() event is not working in JavaScript for dynamic button in my code
- Do not add a function in a loop
- Delegate
Have a look here. There are MANY issues, I have addressed a few of them
You MAY want to do
button.setAttribute("data-code",item.code);
instead of
button.id = i + "-cmd";
// function.js
const content = document.getElementById("content");
content.addEventListener("click",function(e) {
const tgt = e.target, // the element clicked
id = tgt.id; // the ID of the element
if (id.indexOf("-cmd") !=-1) { // is that element one of our buttons?
// get the name of the article from the button - this could also be a data attibute
var pos = id.split("-")[1];
addToCart(pos);
}
})
function chargerArticles() {
const myShoppingCart = catalogArray.map(function(item, i) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
// here would be a good place to add item.name or something
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
content.appendChild(articles) // ???
})
}
function searchInCart(name) {
return myCartArray.filter(function(x) {
return x.name === name
})[0];
}
Related Topics
Determine Original Size of Image Cross Browser
Es6 Variable Import Name in Node.Js
JavaScript Require() Function Giving Referenceerror: Require Is Not Defined
How to Make JavaScript Object Using a Variable String to Define the Class Name
Removing # from Url in Angularjs While Having .Run in Routes
How to Fix Navigator/Window/Document Is Undefined in Nuxt
How Does _Proto_ Differ from Constructor.Prototype
Web Workers Without a Separate JavaScript File
Expression Inside Switch Case Statement
How to Enable Cors Nodejs with Express
How to Query Mongodb Objectid by Date
Retrieving File Names Out of a Multi-File Upload Control with JavaScript
Why Does Jquery Only Affect the First Div Element