alin dradici alin dradici - 26 days ago 18
Javascript Question

Button event handling

I have this div that I am fetching from a database

'<div class="column">'+
'<div>'+ '<img src='+aparat.imagine+' width="150" height="140" />' +'</div>'+
'<div>'+ aparat.nume + '</div>' + //functia care le aranjeaza
'<div id="pret">'+ aparat.pret +'&nbsplei' + '</div>'+
'<div>'+'<button data-value="'+aparat.id+'" class = "comanda">'+'Comanda!'+'</button>'+'</div>'
+ '</div>';


and the event handler:

$(document).ready(function(){
$('.comanda').click( function() {
alert('button clicked');
});
});


The problem is, when I click the button nothing happens, what am I doing wrong?

Answer

If your database data is loaded after the page has fully loaded you'd better use on instead of click as shown, because there's a chance you are attaching an event handler to an element that doesn't yet exist.

$('body').on("click", ".comanda", function() {
    alert('button clicked');
});
Comments