Home  >  Q&A  >  body text

How to listen for specific click events but suppress others?

My web application contains an HTML table where each row is linked to a specific URL:

<table>
  <tr data-url="https://www.google.com">
    <td>Google</td>
  </tr>
  <tr data-url="https://www.yahoo.com">
    <td>Yahoo</td>
  </tr>
</table>

Here's the Javascript to make it work:

const rows = document.querySelectorAll('table tr[data-url]');

rows.forEach(row => {
  row.addEventListener('click', function() {
    handleClick(row);
  });
});

function handleClick(row) {
  const url = row.dataset.url;
  window.document.location = url;
}

This code works great.

Now my client wants me to add checkboxes to these table cells. (I won’t go into details as to why.)

How to suppress redirect when checkbox is selected?

thanks for your help.

P粉199248808P粉199248808178 days ago332

reply all(1)I'll reply

  • P粉980815259

    P粉9808152592024-04-05 11:52:20

    You can check if the target of the event is not a checkbox.

    rows.forEach(row => {
      row.addEventListener('click', function(e) {
        if (!e.target.matches('input[type=checkbox]')) handleClick(row);
      });
    });
    

    reply
    0
  • Cancelreply