1

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?

alin dradici
  • 201
  • 2
  • 4
  • 11

1 Answers1

2

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');
});
Angel Politis
  • 10,955
  • 14
  • 48
  • 66