1

I have a simple table and I write some JS code in order to achieve that whole tr become a data-href. Everything works very nice except for one thing.

Now the whole row is clickable and that is fine, but there is a small issue, if you click on the delete button, it takes you to the update page (data-href), and I want to avoid that. So my question is how can I modify that code for the whole row to stay clickable except that delete button?

Here is my code:

$("tr").each(function() {
    const $tr = $(this);
    $tr.attr("data-href", $tr.find("a").attr("href"))
})

$('*[data-href]').on('click', function() {
    window.location = $(this).data("href");
});
.modal {
  padding:5px;
  background-color:red;
  color:#fff;
  cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table>
   <tr>
      <td>Name</td>
      <td> Age</td>
      <td>
         <a href="/update/1">Update</a>
         <a data-toggle="modal" class="modal" data-target="#deleteModal">Delete</a>
      </td>
   </tr>
</table>

Can somebody try to help me with this?

1 Answer 1

1

To achieve this you can use the is() method to determine what element within the tr was clicked on. If it was an a element then you can prevent the window.location from being updated.

Also note that you can update the data-href of each tr using an implicit loop which makes the code slightly more succinct. Try this:

$('tr').attr('data-href', function() {
  return $(this).find('a').attr('href');
});

$('*[data-href]').on('click', function(e) {
  if (!$(e.target).is('a')) {
    window.location.assign($(this).data("href"));
  }
});
.modal {
  padding: 5px;
  background-color: red;
  color: #fff;
  cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<table>
  <tr>
    <td>Name</td>
    <td>Age</td>
    <td>
      <a href="/update/1">Update</a>
      <a data-toggle="modal" class="modal" data-target="#deleteModal">Delete</a>
    </td>
  </tr>
</table>

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for this code. This code works but if I put an icon inside the button, it does not work, here is a fiddle: jsfiddle.net/subg8p16/5 When you click on the icon it redirects you
In that case you need a tweak to the logic so that it excludes the a and any child element within it: jsfiddle.net/RoryMcCrossan/mq12bLgz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.