Select button from div inside dynamic table

I need to add a click event handler for a button inside a div that is inside a table. How do I get to it using jQuery. Here is my div:

<div id = 'fromServer'></div>

      

This is how I fill it in:

function onSuccess(response) {
    p = response;   //p is global for debugging! 
    resultsArray = response.results;
    str = '<table id=\'mytable\'>';
    str += '<tr><td class =\'title\'>Album</td>';
    str += '<td class =\'title\'>Track Name</td>';
    str += '<td class =\'title\'> <button id =\'save\'>Save</button></td></tr>';

    for (i = 0; i < resultsArray.length; i++) {
        str += '<tr><td>' + '<img src=\'' + resultsArray[i].artworkUrl100 +'\' height=\'100\' width=\'100\''  +  '</td>';
        str += '<td class=\'albumName\'>'  + resultsArray[i].trackName.substring(0,30) + '</td>';
        str +=   '<td> <input type=\'checkbox\' class =\'checkbox\' name=\'' + i + '\'></td></tr>';
    }
    str += '</table>';
    $('#fromServer').html(str);
}

      

This is how it looks:

enter image description here

Now I want to add a click event handler for the save button, how can I do that? Here is my attempt but it doesn't work.

$('#fromServer').find("#mytable").find("#save").bind('click', saveButtonEventHandler);

//Event Handlers
function saveButtonEventHandler(evt) {
    alert("Button pressed!");
}

      

+3


source to share


2 answers


Since the Table and Save buttons are dynamically added to the DOM, you'd be better off using a delegated event handler for this:



$('#fromServer').on('click', '#save', saveButtonEventHandler);

      

+1


source


It looks like the content is loaded with ajax. you can use the function below.



$(document).on("click", '#save', function(event) { 
    alert("button pressed");
});

      

+5


source







All Articles