Toadums
Toadums

Reputation: 2812

How to get the table cell of a row that was clicked with JQuery

I have a table in HTML, and I have an onclick event for its rows.

I was wondering if it was possible to find out which cell of the row was clicked, without having a seperate handler for each cell?

I have a table:

<tr class="new_row">
   <td class="date">date</td>
   <td class="name">name</td>
   <td class="delete">delete</td>
</tr>

and jquery:

$(".new_row").click(function(){
   if(delete was clicked){
       delete the row
   }
});

That is what I want to do basically, detect if the delete cell was clicked.

Is this possible?

Upvotes: 1

Views: 3349

Answers (3)

Adil
Adil

Reputation: 148110

You can do it like this

Live Demo

$(".new_row").click(function(event){       
    if($(event.target).text() == 'delete')
    {       
      $(this).remove();      
    }
});

Upvotes: 3

Zbigniew
Zbigniew

Reputation: 27584

Firstly you should not define more than one element with same id, it will cause trouble, you can replace id='delete' with class='delete'.

// on click td with class delete:
$("td.delete").click(function(){
   //delete was clicked so remove tr
   $(this).parent().remove();
});

Upvotes: 5

Dancrumb
Dancrumb

Reputation: 27529

Look at the id of the event.target. If it matches delete, then you can process a delete.

However, since this in a table, I'm guessing that you have multiple rows. If this is the case, does that mean that you have multiple cells with the same ID? If so, this isn't valid HTML and it could cause problems with your jQuery code, when you try to use CSS selectors.

Upvotes: 1

Related Questions