Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Table Row Click Event also firing when i click a link

Here is what i have so far, getting the row number is working great but i need to make it so that when i click on the link in the table, it doesnt fire the code inside the function.

<table>
  <tr class="row">
    <td>A</td>
    <td><a class="link" href="foo.html">Foo</a></td>
  </tr>
  <tr class="row">
    <td>B</td>
    <td><a class="link" href="Bar.html">Bar</a></td>
  </tr>
</table>


<script>
$(function(){
    $('.row:not(.link)').click(function(){
        var $row = $(this).index();
    });
});
</script>
like image 304
Brandon Avatar asked Jun 13 '11 13:06

Brandon


2 Answers

The selector .row:not(.link) will select all elements that have a class "row" and don't have the class "link", which is not what you are looking for.

You need to use event.stopPropagation within the click event of the a.link elements so that the click event is not propagated to the parents, which includes row.

Try this:

<table>
    <tr class="row">
        <td>A</td>
        <td><a class="link" href="foo.html">Foo</a></td>
    </tr>
    <tr class="row">
        <td>B</td>
        <td><a class="link" href="Bar.html">Bar</a></td>
    </tr>
</table>

<script> 
    $(function(){     
        $('.row').click(function(){         
            var $row = $(this).index();     
        }); 
        $('.row .link').click(function(e){
            e.stopPropagation(); 
        });
    }); 
</script>
like image 200
Chandu Avatar answered Oct 08 '22 10:10

Chandu


Just a bit late, but this is first link in Google I opened in search for solution to relative topic. So, it may become useful for someone:

$(".clickableRow").click(function(e) {
  if (e.target.nodeName != "A") {
    window.document.location = $(this).attr("href");
  }
});

Links in a row, I mean standart , will work as usual, and this example markup will have three independent link activations:

<tr class="clickablerow" href="profile.html">

  <td>John Doe, the VP</td>
  <td><a href="print.html" target="_blank">Print</a><a href="chat.html" target="_blank">Chat</a></td>
    
</tr>
like image 33
ermushko Avatar answered Oct 08 '22 10:10

ermushko