Button in an interactive table cell

I have a table cell that is clickable and fires a jQuery event when clicked. Inside this cell, I also have a button that has a different jQuery event when clicked. The problem is that when a button is pressed, both the cell events and the buttons are triggered.

For instance:

<script> $(document).ready(function () { $('#cell').click(function () { alert('cell clicked'); }); $('#button').click(function () { alert('button clicked'); }); }); </script> <table> <tr> <td id="cell"> <button id="button">go</button> </td> </tr> </table> 

How can I prevent a cell click event from triggering when a button is clicked?

+4
source share
4 answers

You can use stopPropagation() , which will allow you to stop the event from stopPropagation() in the parent dom.

Example

 $('#button').click(function (e) { e.stopPropagation(); alert('button clicked'); }); 

set table width to 100% and test it.

Test code

 <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(function() { $('#cell').click(function () { alert('cell clicked'); }); $('#button').click(function (e) { e.stopPropagation(); alert('button clicked'); }); }); </script> <table width="100%"> <tr> <td id="cell"> <button id="button">go</button> </td> </tr> </table> 
+6
source

stop the event propagation called event bubbling to the parent :

 $('#button').click(function (e) { e.stopPropagation(); alert('button clicked'); }); 
+2
source

You need to use

 stopPropagation 

This example should fix this:

 $(document).ready(function () { $('#cell').click(function () { alert('cell clicked'); }); $('#button').click(function (e) { e.stopPropagation(); alert('button clicked'); }); }); 

That should fix it.

+2
source
 $(document).ready(function(){ $('#cell').click(function(event){ if($(event.target).is('#button')){ event.stopPropagation(); } }); }); 
+2
source

All Articles