I have a table
<table id="favoriteFoodTable"> <th> Food Name: </th> <th> Restaurant Name: </th> <th> </th> <?php while ($row = $foods->fetch()) { ?> <tr> <td> <?php echo $row['foodName']; ?> </td> <td> <?php echo $row['restaurantName']; ?> </td> <td> <a class="deleteLink" href="" >delete</a> </td> </tr> <?php } ?> </table>
I use this jquery function so when a user click on delete, the background of the row will change and the row then will delete
$(document).ready(function() { $("#favoriteFoodTable .deleteLink").on("click",function() { var td = $(this).parent(); var tr = td.parent(); //change the background color to red before removing tr.css("background-color","#FF3700"); tr.fadeOut(400, function(){ tr.remove(); }); }); });
just the background is changing but the row is not deleted, why? how to solve?
The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements. Parameters: It accepts single parameter selector which is optional.
Delete a row or column Select a row or column that you want to delete. Press Backspace, or select the Table Tools Layout tab >Delete, and then select an option. Note: In Excel, select a row or column that you want to delete, right-click and select Delete , and choose the option you want.
To delete rows in a table in JavaScript, use the DOM deleteRow() method.
The jQuery function removes all the rows except the first one using the remove() method. Syntax: $('#btn').
The row is deleted but as clicking makes you follow the link, it's immediately restored when the page is refreshed.
Add return false;
or event.preventDefault();
at the end of the callback to prevent the default behavior :
$(document).ready(function() { $("#favoriteFoodTable .deleteLink").on("click",function() { var tr = $(this).closest('tr'); tr.css("background-color","#FF3700"); tr.fadeOut(400, function(){ tr.remove(); }); return false; }); });
Demonstration
Note that I used closest
for a more reliable code : if another element comes in between, the tr
will still be found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With