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!
我有一个表单,用户可以在其中动态添加行并删除它们。我的问题是删除功能仅在单击FIRST行上的删除按钮时有效,并且它删除了最后一行,显然是因为我写了tr:last。我已经尝试了我能想到/在互联网上找到的每一个组合,我似乎无法弄清楚如何删除最后一行以外的行。理想情况下,我想在每一行上都有一个删除按钮,删除按钮会从表中删除该特定行而不是最后一行。任何帮助,将不胜感激。谢谢!
<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"/>
1 个解决方案
#1
4
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');
}
});
#1
4
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');
}
});