1

I have a html table like so -

<table class="table" id="myTable">
<thead>
   <th>Email</th>
   <th>Delete</th>
</thead>
<tbody>
</tbody>

I can dynamically add to the table doing this:

var tbody = $('#myTable').children('tbody');   
var table = tbody.length ? tbody : $('#myTable');
table.append("<tr><td>"+user_email+"</td><td><input type='button' value='Del' id ='"+user_id+"'class='btn btn-danger btn-sm'></td></tr>");

But when I try to remove a row doing this:

$('input[type="button"]').click(function(e){
   $(this).closest('tr').remove()
})

The row don't remove. How do I resolve this?

shekwo
  • 1,411
  • 1
  • 20
  • 50

2 Answers2

1

Sometimes not using jQuery may help you understand what's actually happening. Here's a snippet that may be helpful.

// add the listener to the document (event delegation)
document.addEventListener("click", deleteRow);

// add a first row
addRow(document.querySelector("#myTable"));

function deleteRow(evt) {
  // read data-property (data-delete or data-add)
  if (evt.target.dataset.delete) {
    // retrieve the row to delete
    const row2Delete = evt.target.closest("tr");
    // remove that from *its parent* (the table)
    row2Delete.parentNode.removeChild(row2Delete);
  } else if (evt.target.dataset.add) {
    addRow(document.querySelector("#myTable"));
  }
  return true;
}

function addRow(toTable) {
  // create a row
  const row = document.createElement("tr");
  // create 2 cells
  const cell1 = document.createElement("td");
  const cell2 = cell1.cloneNode(true);
  //create a button for the second cell
  const bttn = document.createElement("button");
  bttn.dataset.delete = "1";
  bttn.textContent = "delete";
  // fill the first cell with a random e-mailaddress
  cell1.appendChild(document.createTextNode(`someUser${
        Math.floor(1 + Math.random() * 10000000)}@somewhere.net`));
  // append button to cell2        
  cell2.appendChild(bttn);
  // append cells to row
  row.appendChild(cell1);
  row.appendChild(cell2);
  // append row to table
  toTable.appendChild(row);
}
<button data-add="1">Add a row</button>
<table class="table" id="myTable">
<thead>
   <th>Email</th>
   <th>Delete</th>
</thead>
<tbody>
</tbody>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • 1
    Is there any problem with my current JQuery? – shekwo May 10 '20 at 12:14
  • Well [@Roko C Buljan](https://stackoverflow.com/users/383904/roko-c-buljan) explained that already. Just liked to demonstrate that [you may not need jquery](http://youmightnotneedjquery.com/) and sometimes doing things in plain vanilla js gives more understanding of what you or js are/is actually doing. But hey, do what you like best, I'm not imposing things here. – KooiInc May 10 '20 at 12:52
1

You were pretty close, since the TR and the button are dynamically generated,
use the .on() method:

$("#myTable").on("click", "input[type='button']", function(e){
   $(this).closest('tr').remove()
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313