Gandalf
Gandalf

Reputation: 930

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.

Upvotes: 3

Views: 1739

Answers (2)

dnetix
dnetix

Reputation: 330

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.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 1

Related Questions