Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I exclude a button click inside a TR click event?

I am currently highlighting a table row when selected but in one of the cells I have a button. When I click the button I am triggering the table row click event. Is it possible to seperate the two?

My two calls currently look like this:

$('table.table-striped tbody tr').on('click', function () {
   $(this).find('td').toggleClass('row_highlight_css');
}); 


$(".email-user").click(function(e) {
    e.preventDefault();
    alert("Button Clicked");
});

My HTML looks like this:

<table class="table table-bordered table-condensed table-striped">
  <thead>
    <tr>
      <th>col-1</th>
      <th>col-2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Some Data</td>
      <td><button class="btn btn-mini btn-success email-user" id="email_123" type="button">Email User</button></td>
    </tr>
  </tbody>
</table>

Any idea how I might stop the button click event from triggering the row click event?

like image 233
user1216398 Avatar asked Nov 27 '12 16:11

user1216398


People also ask

How do I trigger a click event without clicking?

If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.

How do you make onclick events only work once?

There are a number of ways to allow only one-click in Javascript: Disable the button after clicking on it. Use a boolean flag to indicate “clicked”, don't process again if this flag is true. Remove the on-click attribute from the button after clicking once.


1 Answers

You have to use stopPropagation:

$(".email-user").click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    alert("Button Clicked");
});

(See also : What's the difference between event.stopPropagation and event.preventDefault?)

like image 86
Samuel Caillerie Avatar answered Sep 28 '22 07:09

Samuel Caillerie