Otonel Otonel - 4 years ago 197
Javascript Question

On click delete table row in Jquery

I have this code Ajax/Jquery that creates a dynamic table with rows based on data retrieved from the database. When creating the table buttons are also created dynamically for each row.
In addition to the above I would like to be able to call a function for thees buttons. For example if the first table row button has an id of 0, then clicking on button with id 0 will call a function that would take the id of the first row, and perform a database delete function.
How can I achieve this?

Here is my code where the table is created dynamically:

success: function(controller_data)
{ JSON.stringify(controller_data);

var tr;
for (var i = 0; i < controller_data.length; i++) {

tr = $('<tr/>');
tr.append("<td><input name = \"radios\" value = tablebutton"+i+" id=tablebutton"+i+" type=\"button\"></td>");
tr.append("<td>" + controller_data[i].id + "</td>");
tr.append("<td>" + controller_data[i].question + "</td>");
tr.append("<td>" + controller_data[i].image + "</td>");
tr.append("<td>" + controller_data[i].answer1 + "</td>");
tr.append("<td>" + controller_data[i].answer2 + "</td>");
tr.append("<td>" + controller_data[i].answer3 + "</td>");
tr.append("<td>" + controller_data[i].answer4 + "</td>");
$('table').append(tr);
}
}


enter image description here

Answer Source

You should use event delegation on() since you deal with fresh DOM added dynamically to the page, e.g :

$('body').on('click', 'input[id^="tablebutton"]', function(){
     //Call your function
})

Try to add class to identify td that contain row id e.g :

tr.append("<td class='row-id'>" + controller_data[i].id + "</td>");

Full code :

$(function(){ //Ready function
     $('body').on('click', 'input[id^="tablebutton"]', function(){
         var row_id = $(this).parents('tr').find('.row-id').text(); //get the id
         myFunction(row_id);
     })
})

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download