3

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);
});
});
Byate
  • 123
  • 1
  • 2
  • 16

2 Answers2

9

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);
   });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
3

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

$('#table').on('click', 'button', function(){
j08691
  • 204,283
  • 31
  • 260
  • 272