Gasp0de Gasp0de - 8 days ago 7
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

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))
    .append($("<th/>").html("name"))
    .append($("<th/>").html("zutaten"))
    .append($("<th/>").html("name"))
    .append($("<th/>")
      .append($("<button/>")
        .text("Delete")
        .on("click", function(){
          showPwdDialog(i);
        })
      )
    );

  /* add row to table here */
}

jsfiddle

Comments