views:

1211

answers:

3

I have the following code:

$("#Table1 tbody").children().each(function(e){
$(this).bind('click', 
            function(){
                // Do something here
            }, 
            false) 
});

The Table1 html table has 2 columns; one for Names and one for a <button> element.

When I click on a table row, it works fine. When I click on the button, the button code fires; however, so does the row code.

How can I filter the selector so the button doesn't trigger the parent element's click event?

A: 

Is it possible to remove the button code and just run the row code, therefore kind of using event bubbling.

Another couple options:

  • can you add a class to the TD that has the button in it and in the selector, do '[class!="className"]'
  • maybe try event.preventDefault(). You can see it being used here. this way you can prevent the default action that is triggered when the button is clicked, although I'm not sure if it will completely prevent the bubbling.
Darryl Hein
Ultimately, the row on click is a selection action while the button's onclick is a deletion action. I haven't been able to figure out a good way to make such works.
JamesEggers
+7  A: 

This is what you want.

It's stopPropogation that will stop the parents.

<table>
  <tr>
    <td>The TD: <input type="button" id="anotherThing" value="dothis"></td>
  </tr>
</table>

<div id="results">
  Results:
</div>

<script>

  $(function() {
    $('#anotherThing').click(function(event) {
       $('#results').append('button clicked<br>');
       event.stopPropagation();       
    });
    $('td').click(function() {
       $('#results').append('td clicked<br>');

    });
  });

</script>

Here's a link to an example of it working as well:

http://jsbin.com/uyuwi

You can tinker with it at: http://jsbin.com/uyuwi/edit

altCognito
+2  A: 

You could also do something like this:

<table id="Table1">
        <tbody>
            <tr id="tr1">
                <td>
                    The TD: <input type="button" id="button1" value="dothis"/>
                </td>
            </tr>
            <tr id="tr2">
                <td>
                    The TD: <input type="button" id="Button2" value="dothis"/>
                </td>
            </tr>
        </tbody>
    </table>

the supporting JS

        $('#Table1 tr').bind('click', function(ev) { return rowClick($(this), ev); });  //Bind the tr click
        $('#Table1 input').bind('click', function(ev) { return buttonClick($(this), ev); })  //Bind the button clicks

        function rowClick(item, ev) {
            alert(item.attr('id'));
            return true;
        }

        function buttonClick(item, ev) {
            alert(item.attr('id'));
            ev.stopPropagation();

            return true;
        }
Rick Hochstetler