Reputation: 41
I dynamically create a button in the way I found in the Internet:
...
outPut +=
"<div class=\"col-lg-4 col-md-6 mb-4\">" +
"<div class=\"card h-100\">"+
"<a href=\"#\"><img class=\"card-img-top\" src=\"http://placehold.it/700x400\" style=\"height: 50%; width:50% \" alt=\"\"></a>"+
"<div class=\"card-body\">"+
"<h4 class=\"card-title\">"+
"<a href=\"#\">"+ nome +"</a>"+
"</h4>"+
"<h5>"+ preco +"</h5>"+
"<p class=\"card-text\">"+ descricao +"</p>"+
"</div>"+
"<div class=\"card-footer\" >"+
"<button type=\"button\" class=\"btn btn-success-cart\" data-id=\"" + id + "\" data-nome=\"" + nome + "\" data-descricao=\"" + descricao + "\" data-preco=\"" + preco + "\">+ Carrinho</button>"+
"</div>"+
"</div>"+
"</div>";
...
$("#divCards").html(outPut);
And Imply the method of click on each one in this way:
$(".btn-success-cart").click(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();
});
But nothing happens when I click the generated buttons.
Upvotes: 2
Views: 1112
Reputation: 21
I know it's a bit late to answer here but similar situation happened to me and above accepted answer worked sort of. But it fires the event multiple times because my script included to call that function which creates click event several times for different occasions. So each call would create the click event repeatedly. Then when a user click the button, the function will be called multiple times. Therefore I had to off click then on click. Just adding this answer so that anyone else has same issue with me may get help.
('#divCards').off('click', '.btn-success-cart').on('click', '.btn-success-cart', (event) => {
......
}
});
Upvotes: 0
Reputation: 24146
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();
});
Upvotes: 4