0

I have one event attached to on row click and one event attached to on checkbox change inside the row.

How to prevent that row click is fired first?

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

$(document).on('change', 'table tr input[type="checkbox"]', function() {
  console.log('chk');
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <table>
    <tr>
      <td>
        <input type="checkbox">
      </td>
    </tr>
  </table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
RMontes13
  • 2,138
  • 3
  • 16
  • 23

3 Answers3

2

Change the event you're handling on the inner element from change to click.

The change event doesn't fire until after the click event. The click event is triggered on the checkbox, then bubbles out to the row. When that completes, the change event is triggered on the checkbox.

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

$(document).on('click', 'table tr input[type="checkbox"]', function() {
  console.log('chk');
})
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <table>
    <tr>
      <td>
        <input type="checkbox">
      </td>
    </tr>
  </table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Add click event for checkbox also to stop event propagation.please check this out for the hint.

https://stackoverflow.com/a/54550360/3729024

Himen Suthar
  • 80
  • 1
  • 3
  • 11
0

Using jquery selector :not to exclude checkbox for a tr click and then stop propagation of a child element event to the parent tr.

$(document).on('click', 'table tr :not(input[type="checkbox"])', function(e) {
  console.log('row');
});

$(document).on('click', 'table tr input[type="checkbox"]', function(e) {
  console.log('chk');
  e.stopImmediatePropagation();
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <table>
    <tr>
      <td>
        <input type="checkbox">
      </td>
      <td>another td</td>
    </tr>
  </table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>
Haider Ali
  • 1,081
  • 8
  • 23