Reputation: 121
I have a form in which the user can dynamically add rows and delete them. My problem is that the delete function only works when clicking the delete button on the FIRST row, and it deletes the LAST row, obviously because I have written tr:last. I have tried every combination I can think of/find on the internet and I cannot seem to figure out how to delete a row other than the last row. Ideally, I would like a delete button on every row and the delete button would delete that specific row from the table instead of just the last row. Any help would be appreciated. Thank you!
<script>
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.orderForm tr:last').after(appendRow);
});
$(".deleteThisRow").click(function(){
if($('.orderForm tr').size()>1){
$('.orderForm tr:last').remove();
}else{
alert('One row should be present in table');
}
});
});
</script>
<table class="orderForm" id="orderForm" width="100%">
<tr class="row">
<td>
<div class="pure-control-group">
<label>Product or Service</label><select name="product[]" id="product">
<option value=""></option>
<?php while($productRow = mysql_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option>
<?php } ?>
</select>
</div>
<div class="pure-control-group">
<label>Price</label><input type="text" id="price" name="price[]">
</div>
<input type="button" class="deleteThisRow" id="deleteThisRow" value="Delete"/>
</td>
</tr>
</table>
<input type="button" id="btnAddMore" value="Add Product or Service" class="pure-button"/>
Upvotes: 2
Views: 618
Reputation: 82231
You need to use event delegation for attaching events to dynamically added elements. Use:
$("body").on('click','.deleteThisRow',function(){
if($('.orderForm tr').length>1){
$(this).closest('tr').remove();
}else{
alert('One row should be present in table');
}
});
Upvotes: 4