Gasp0de Gasp0de - 1 year ago 100
jQuery Question

Create a Button dynamically which will call a method with a different parameter each time

I'm creating rows that i add to an existing table using jQuery. I want each of these rows to contain a delete button, that calls a method which asks for a passphrase and then deletes this row. For that, i create a new line like this:

$('tbody').append('<tr id="row' + index + '"><th>' + name + '</th>' + '<th>' + zutaten + '</th>' + '<th>' + foodtype + '</th>' + '<th><button onclick="showPwdDialog(' + index + ');">Delete</button></th></tr>');

As you can see, I am trying to call the showPwdDialog method with the rows index as a parameter. However, this doesn't seem to work. What am i doing wrong?

Answer Source

I don't think your onclick handler is being bound properly when constructing the element via html fragments like you are.

How about this instead?

var index = 0;

function showPwdDialog(i) {
  if (confirm("Delete this row?"))
    $("#test #row"+i).remove();

function addRow(){
  var i = ++index;
  var row = $("<tr>")
    .attr("id", "row"+(i))
        .on("click", function(){

  /* add row to table here */


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