How to Write an Onclick Function for a Dynamically Generated Button

How to write an onclick function for a dynamically generated button

The easiest way is to add an event listener the button variable like so:

const btn = document.createElement('button');
btn.innerText = "Click me!";
btn.addEventListener('click', function(event) {
console.log('Fired!');
});

Assigning onclick function to dynamically created button

This won't work. The two statements should be separate. You cannot pass the event handler as an argument to the .html() function. You need to do this way:

$(function() {  $("#buttons_div").html('<input type="button" value="Click me" id="button1" />');  $("#buttons_div").on("click", "#button1", function() {    alert("alert")  });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="buttons_div"></div>

Setting a onClick function to a dynamically created button, the function fires onload

When you write
removeButton.onClick = RemoveFromWishList(item.name); you are assigning the return value of the function call to the onClick event. Instead you can write

removeButton.onClick = function() { RemoveFromWishList(item.name);}

You should assign a function to the onClick event listener.

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 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.

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
});

How to add onclick event to dynamically generated HTML elements

You have to add the event listener again to each element you add. But not like JakeCroth tried to explain (at least if I understand you correctly). Instead, try it like this:

let lst = document.querySelector('.lst');let btn = document.querySelector('.btn');
function addListItem() { let li = document.createElement('li'); li.innerHTML = "New element"; li.addEventListener('click', testTheEventListener); lst.appendChild(li);}
function testTheEventListener() { console.log("The event listener works!");}
document.querySelectorAll('li').forEach(li => { li.addEventListener('click', () => { testTheEventListener(); });});
<ul class='lst'>  <li class="listItem">First</li>  <li class="listItem">Second</li>  <li class="listItem">Third</li></ul>
<button onclick="addListItem()" class='btn'>Add item</button>

Adding onClick event to dynamically generated buttons?

You can do this by using a Javascript feature called "event bubbling". Ancestor elements are notified of events on their descendent elements.

In this case, you can attach a click handler to the body element and all clicks on those buttons will trigger an event handler. The nicest way to do this in jQuery is to use the on method:

$(document.body).on('click', 'button', function() {
alert ('button ' + this.id + ' clicked');
});

This will work no matter when the elements are created – before or after the elements were created.

This does exactly the same thing as the live method, but live uses on behind the scenes and is far less efficient and flexible.



Related Topics



Leave a reply



Submit