alin dradici alin dradici - 1 year ago 101
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="''" class = "comanda">'+'Comanda!'+'</button>'+'</div>'
+ '</div>';

and the event handler:

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

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

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download