Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which <td> is clicked

I have the following case: I have a with some and . I need to detect which was clicked (eventually get the Id). I have build the following JS Fiddle as a reference.

jQuery(document).ready(function() { 
    $(".table").find("tr").click( function(){
        alert("<tr> clicked");
        var td2 = $(this).find(".td2:first").text();
        alert(td2);
    });
});

I have a .click() event and I am doing some actions when is clicked but I need to detect if a specific <td> is clicked in order to exclude that TD. Basically when any is clicked some actions should be done (unless a specific <td> is clicked, and in that case nothing should be done)

What do you think?

like image 866
TerminatorX Avatar asked Feb 09 '23 02:02

TerminatorX


1 Answers

If you want to exclude the clicks in td2, then in the click handler you can use event.target to get the actual element that is clicked.

jQuery(document).ready(function() {
  $(".table tr").click(function(e) {
    if ($(e.target).closest('td').is(':nth-child(2)')) {
      snippet.log('td2 clicked');
      return;
    }
    snippet.log("<tr> clicked");
    var td2 = $(this).find("td:nth-child(2)").text();
    snippet.log('td2: ' + td2)
  });
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table">
  <tr>
    <td class="td1"></td>
    <td class="td2">A</td>
    <td class="td3">B</td>
    <td class="td4">C</td>
    <td class="td5">D</td>
  </tr>
  <tr>
    <td>1</td>
    <td>A1</td>
    <td>B1</td>
    <td>C1</td>
    <td>D1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>A2</td>
    <td>B2</td>
    <td>C2</td>
    <td>D2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>A3</td>
    <td>B3</td>
    <td>C3</td>
    <td>D3</td>
  </tr>
</table>
like image 62
Arun P Johny Avatar answered Feb 11 '23 15:02

Arun P Johny