Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery delete table row

Tags:

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?

like image 471
user2059935 Avatar asked Mar 24 '13 21:03

user2059935


People also ask

How do I remove a row from a table in jQuery?

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.

How do you delete a row in a table?

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.

How do you delete a row in a table using JavaScript?

To delete rows in a table in JavaScript, use the DOM deleteRow() method.

How we can delete all table rows except first one using jQuery?

The jQuery function removes all the rows except the first one using the remove() method. Syntax: $('#btn').


1 Answers

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.

like image 167
Denys Séguret Avatar answered Nov 15 '22 12:11

Denys Séguret