Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a particular row of a table using jQuery?

I have a table like the following:

HTML:

<table id="data-filter">
  <tr>
     <td>1</td>
     <td>Harry Potter</td>
     <td><span class="delete"></span></td>
   </tr>
   <tr>
     <td>2</td>
     <td>Frodo Baggins</td>
     <td><span class="delete"></span></td>
   </tr>
</table>

If the user clicks "x" in any row, that particular row will be deleted. I am able to find which row is clicked, but I am unable to find exactly which rows "x" is clicked. My jQuery and CSS code are below:

jQuery:

$(document).on('click', '#data-filter tr', function() {
    rn = this.rowIndex;
    alert('You clicked row: '+rn); // do something to remove this row
});

CSS:

.delete:after { content:"x";}

I want to trigger the delete event, only when the user clicks a particular row's "x", not the whole row or just any part of the row. I think I may be just missing the correct selector for this, but I am not sure.

like image 605
Gandalf Avatar asked Dec 05 '25 04:12

Gandalf


2 Answers

You can use this to refer to the element targeted by the handler so

$(document).on('click', '#data-filter tr .delete', function() {
    $(this).closest('tr').remove()
});

Also from what I can see, you need to delete the row when you click the delete button so you need to add the handler to the delete element and then use .closest() to find the tr element where the delete button is present then call .remove() to delete that row

like image 150
Arun P Johny Avatar answered Dec 07 '25 17:12

Arun P Johny


I was looking at your problem and I have a solution:

$(document).on('click', '#data-filter tr .delete', function() {
            this.parentElement.parentElement.remove();
        });

And you need to remove the hashtag on your table id (should be just "data-filter") thats how you call it from jQuery not how it's declared on HTML

What I'm doing with the function its set the listener in the span not on the row and calling the parent nodes until the TR

Hope that works for you.

like image 24
dnetix Avatar answered Dec 07 '25 17:12

dnetix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!