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);
});
});
1
  • 2
    Not again! Use delegated event handlers ? Commented Jan 7, 2014 at 17:18

2 Answers 2

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);
   });
});
Sign up to request clarification or add additional context in comments.

1 Comment

+1, but use the selector #table instead of document. You should ideally pick the closest container element.
3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.