JamesEggers
JamesEggers

Reputation: 12935

jQuery Children selector question

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?

Upvotes: 4

Views: 2234

Answers (3)

Rick Hochstetler
Rick Hochstetler

Reputation: 3123

You could also do something like this:

$('#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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

Upvotes: 2

cgp
cgp

Reputation: 41381

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

Upvotes: 7

Darryl Hein
Darryl Hein

Reputation: 144987

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.

Upvotes: 0

Related Questions