1

I have a table row with one of the td containing a button. I want to be able to click the tr and have that trigger a function. However, I do not want this function to be triggered if the button within the td is clicked. My current method is by using a :not selector on the td of the button but i would prefer to use the button itself. The class noclick is the class of the button parent td.

$('#mytable td:not(.noclick)').on('click',function(){

EDIT: for clarification

<tr data-x="test">
  <td>NAme</td>
  <td>Phone</td>
  <td class="noclick"> // this is where the current not selector works
    <button>X</button> // this button is the only place I want the not selector to work
  </td>
</tr>

So to clarify I want a similar process to my posted handler but instead I want the buttons parent td to work for the click function and not work for the button itself.

I have tried a few different things including still using the td but trying to make the td a minimal size. I was not able to get the td to become smaller.

FamousAv8er
  • 2,345
  • 2
  • 9
  • 27

1 Answers1

2

When e.target equals this you clicked on the td element, not a descendant, such as button. In other words the click event is not due to event bubbling.

$('#mytable td:not(.noclick)').on('click',function(e) {
    if(e.target !== this) return;
    console.log('Clicked!!!!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable">
<tbody>
<tr>
  <td>col 1</td>
  <td>col 2</td>
  <td>col 3</td>
  <td>col 4<button class="noclick">No Click</button></td>
  <td>col 5</td>
</td>
<tr>
  <td>col 1</td>
  <td>col 2</td>
  <td>col 3</td>
  <td>col 4<button class="noclick">No Click</button></td>
  <td>col 5</td>
</td>
<tr>
  <td>col 1</td>
  <td>col 2</td>
  <td>col 3</td>
  <td>col 4<button class="noclick">No Click</button></td>
  <td>col 5</td>
</td>
<tr>
  <td>col 1</td>
  <td>col 2</td>
  <td>col 3</td>
  <td>col 4<button class="noclick">No Click</button></td>
  <td>col 5</td>
</td>
</tbody>
</table>

Reference

PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • Thank you for the working solution! I will accept it if you could just provide some explanation about whats going on in the background with `if(e.target !== this) return;`. More specifically what `e` and `e.target` will be. I can edit in the info if necessary. – FamousAv8er Jun 24 '20 at 20:32