3

In the table row I have click event like onclick="trDetailsModal(this, 'id')" and I am showing details in the modal. So inside the tr I have also two buttons under actions td, those buttons are also having onclick event like onclick="deleteRecord('id')";

I am able to see details in a modal by clicking on tr.

Now the problem is when I click one of the buttons the tr onclick also getting triggered and showing details also in model.

So how to stop tr onclick while clicking one of those buttons.

Code:

$content .= '<tr class="trClass" onclick="trDetail(this, '.$val->id.');">';
$content .= '<td>some value</td>';
$content .= '<td><button onclick="deleteRecord('.$val->id.')"></td>';
$content .= '</tr>';

function deleteRecord(id){

  $(".trClass").off("click");
  $("#myModal").hide();

}
mohsin
  • 123
  • 9

2 Answers2

5

That's usually accomplished by calling stopPropagation on the click event of the button, which prevents the event from bubbling.

See example below: you'll notice that when you click the button, you only see the console log of "button clicked", and not "row clicked." This is because the stopPropagation prevented the click event for the tr from firing.

$('tr').on('click', function(e){
  console.log('row clicked');
});

$('.delete').on('click', function(e){
  e.stopPropagation();
  console.log('button clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td> my row </td>
    <td> <button class='delete'>delete</button> </td>
  </tr>
</table>

*Edit: @skapicic's solution of using a data attribute is IMHO a better way of doing it, but if you really want to use an inline event handler, you can do a stopPropagation like this:

$content .= '<td><button onclick="event.stopPropagation(); deleteRecord('.$val->id.')"></td>';

see this answer for more info

David784
  • 7,031
  • 2
  • 22
  • 29
  • is it possible to use it in this way onclick="deleteRecord(id);" function deleteRecord( what to get here ){ what.stopPropagation } – mohsin Jun 24 '20 at 12:20
  • 1
    Yes, it's possible...see [here](https://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute) – David784 Jun 24 '20 at 12:23
  • thanks @David784 that was helpfull – mohsin Jun 24 '20 at 13:03
1

You need the event that has been triggered and you need to stop its propagation

skapicic
  • 209
  • 1
  • 5
  • how to use it with onclick="deleteRecord(id);" function deleteRecord( what to get here ){ what.stopPropagation } – mohsin Jun 24 '20 at 12:15
  • 1
    try refactoring the line to be `$content .= '';` and in deleteRecord `function deleteRecord(event){ event.stopPropagation(); var id = event.target.getAttribute('data-id'); ... }` – skapicic Jun 24 '20 at 12:16
  • thanks skapicic this is good suggestion – mohsin Jun 24 '20 at 13:03