I am trying to create a table that I can add & remove rows from as needed. The table itself is created on the fly with PHP and I have no way of knowing how many cells will be in each table row. So far I have been able to add rows successfully but have been stymied as to how to remove a specific row when the "X" is pressed.
I figure, if I can pass a number to the "remove" function, that can be used to determine what row to delete. I have been attempting to remove the final "td" from the cloned data and replace it with a "td" that contains the correct function argument.
Nothing I've tried has worked thus far. Any suggestions?
HTML
<table class='group'>
<tr class='group_row_0'>
<td>Thing 1</td>
<td>Thing 2</td>
<td>Thing 3</td>
<td>Thing 4</td>
<td>
<a href='#' class='group_remove' onclick='javascript:removeGroupField(0);'>X</a> <!-- The "0" here needs to be replaced with the new row # -->
</td>
</tr>
</table>
<a href='#' class='group_add' onclick='javascript:addGroupField();'>+ Add Row</a>
Javascript:
var row_index = 1;
function addGroupField(){
var last_row = row_index-1;
var rowData = $('.group_row_'+last_row).clone();
rowData.attr('class','group_row_'+row_index);
$('.group').append(rowData);
row_index++;
}
You should try to attach your handlers with Javascript properly, not with inline handlers. Just add a single handler to the table, and when the X
is clicked, remove the row by navigating upwards from the clicked button to the tr
to remove:
$('table.group').on('click', '.group_remove', function() {
const tr = this.parentElement.parentElement;
tr.remove();
});
$('.add').on('click', function (){
const cloned = $('.group tr:last-child').clone();
$('.group').append(cloned);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='group'>
<tr class='group_row_0'>
<td>Thing 1</td>
<td>Thing 2</td>
<td>Thing 3</td>
<td>Thing 4</td>
<td>
<a href='#' class='group_remove'>X</a>
</td>
</tr>
<tr class='group_row_1'>
<td>Thing 1</td>
<td>Thing 2</td>
<td>Thing 3</td>
<td>Thing 4</td>
<td>
<a href='#' class='group_remove'>X</a>
</td>
</tr>
<tr class='group_row_2'>
<td>Thing 1</td>
<td>Thing 2</td>
<td>Thing 3</td>
<td>Thing 4</td>
<td>
<a href='#' class='group_remove'>X</a>
</td>
</tr>
<tr class='group_row_3'>
<td>Thing 1</td>
<td>Thing 2</td>
<td>Thing 3</td>
<td>Thing 4</td>
<td>
<a href='#' class='group_remove'>X</a>
</td>
</tr>
</table>
<div class="add">add row</div>