0

I have two tables: one-column table standing next to the multi-column table. I want to delete a row in a multi-column table by clicking the cell in a one-column table that is standing next to this row.

I am trying to do this by using this code:

$('.my-table').on('click','td .del-row-td',function(e){
  e.preventDefault();
  $(this).closest('tr').remove();
});

Where .my-table is a multi-column table and .del-row-td is a cell in a one-column table. Maybe "closest" does not work if these are two separate objects?

Here is a demo where I am trying to do this. And here is an explanation in the image.

mayua
  • 101
  • 2
  • 8

1 Answers1

1

you need to get the index of the one-column tr and remove the matching multi-column tr

$('#table-del tr').click(function(){
  var trIndex = $("tr", $(this).closest("table")).index(this);
  $($('#my-table tr')[trIndex]).remove()
  $(this).remove();
})

updated fiddle (updated to use on)

some nicer code options to delete the matching tr here

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
  • thank you! It worked with the rows that were there in the beginning. But somehow it does not work for the rows that are added with the "+" button (yellow). Do you have any ideas why is that so? Here is the current version with your code in it: https://jsfiddle.net/mozghovyi/bgfvn8aw/1/ – mayua Apr 30 '18 at 21:03
  • yes, my bad, sorry, changed to use `on`, working version: https://jsfiddle.net/5k0qeoqL/1/ – bresleveloper Apr 30 '18 at 21:06
  • thank you again, I would not guess it! And I hope the last question :) : do you have any idea why "add" button stops adding rows if I delete the top row in the table? I can delete and add any quantity of rows and it works fine, but when I delete the top one - it stops adding rows... – mayua Apr 30 '18 at 21:13
  • since the element for adding columns is hiding it, you gave them all `position:absolute`, which i dont think is recommended, you'll need to find a css solution for that – bresleveloper Apr 30 '18 at 21:18
  • 1
    thank you for noticing it! I will look for the solution. – mayua Apr 30 '18 at 21:39