Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button within clickable table cell

I have a table cell which is clickable and fires a jQuery event when clicked. Within that cell I also have a button, which has another jQuery event when clicked. The issue is, when the button is clicked both the cell and button events are fired.

For example:

<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 the cell click event being fired when the button is clicked?

like image 220
Citrus Avatar asked Mar 04 '13 11:03

Citrus


4 Answers

You can use stopPropagation() which allow you to stop bubbling of event to the parent dom.

Example

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

set the 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>
like image 50
Dipesh Parmar Avatar answered Nov 09 '22 14:11

Dipesh Parmar


stop the event propagation which is called event bubbling to the parent:

$('#button').click(function (e) {
        e.stopPropagation();
        alert('button clicked');
    });
like image 35
Jai Avatar answered Nov 09 '22 15:11

Jai


$(document).ready(function(){
   $('#cell').click(function(event){
     if($(event.target).is('#button')){
         event.stopPropagation();
      }    
   });    
});
like image 44
coolguy Avatar answered Nov 09 '22 16:11

coolguy


You need to use

stopPropagation

This example should fix it:

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

That should fix it.

like image 36
Gary Stevens Avatar answered Nov 09 '22 14:11

Gary Stevens