Byate
Byate

Reputation: 123

jQuery on button click not working after append

I have a web page that queries a database and sends back data via jQuery to an HTML table. I can successfully return results by appending that data to the HTML table, whilst also adding an 'Add to playlist' button on each returned row that is intended to send the data in that row to another page if needs be.

On click of this button, nothing happens on my site (i've set it up to alert me if data is stored in the jQuery variable). I've tested the basic functions in JSfiddle and it works there so I figured there must be a problem with the way tr.append works? Or am I missing something even more obvious with the .on function?

jQuery code that returns data from database:

function (data) {
for (var i = 0; i < data.length; ++i) {
    var tr = $('<tr/>');
    tr.append("<td class='artist'>" + data[i].ARTIST + "</td>");
    tr.append("<td class='title'>" + data[i].TRACKTITLE + "</td>");
tr.append("<td>" + "<button class='send' type='submit'>Add to playlist!</button>" + "</td>");

$('#table').append(tr);
}       

jQuery code that finds data in returned row and stores to variables

$(function(){
     $('button').on('click', function(){
     var tr = $(this).closest('tr');
     var title = tr.find('.title').text();
     var artist = tr.find('.artist').text();
     alert('title: '+title+', artist: ' + artist);
});
});

Upvotes: 3

Views: 14453

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115232

You can do something like this using event delegation,

$(function(){
     $('#table').on('click','button', function(){
     var tr = $(this).closest('tr');
     var title = tr.find('.title').text();
     var artist = tr.find('.artist').text();
     alert('title: '+title+', artist: ' + artist);
   });
});

Upvotes: 9

j08691
j08691

Reputation: 207899

When dynamically adding elements to a document, use .on()'s delegated event handler syntax:

$('#table').on('click', 'button', function(){

Upvotes: 3

Related Questions