2

I have written code so that if the table row is clicked it will act as a link and bring you to a new page, however I also want to have it so they can select rows to do things with. The problem is when they click on the checkbox to select it, it detect that the "row" was clicked and activates the link.

Here is the code I have written

<script>
$(document).ready(function() {$('table[name=$tableName]').DataTable();
            $('table[name=$tableName] tbody').on( 'click', 'tr', function () {
                $(location).attr('href', 'http://stackoverflow.com/');
            })

        });
</script>

I have checkboxes in the first column

enter image description here

The problem is anytime the checkbox is clicked I need it to not redirect the page. Basically if anywhere else is then it will.

Anyone know how I can modify to implement this functionality?

2
  • Looks like that is a label and not a checkbox that is clickable.... Correct? Commented Nov 19, 2019 at 15:21
  • It is a checkbox, it uses semantic UI to turn it into that, as seen here : semantic-ui.com/modules/checkbox.html#toggle Commented Nov 19, 2019 at 15:23

1 Answer 1

5

So check what was clicked and if it it the label/checkbox then ignore it.

$("table tbody").on("click", "tr", function (e) {
  if ($(e.target).is("label,input")) {
    return
  } else {
    console.log("clicked")
  }
})
input[type="checkbox"] {
  display: none
}

input[type="checkbox"]:checked + label {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox" id="cb1"><label for="cb1">CB</label></td>
    <td>HMMMM 1</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="cb2"><label for="cb2">CB</label></td>
    <td>HMMMM 2</td>
  </tr>
<table>

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

2 Comments

Looks great, will accept. In my specific example I don't have a label. It is a regular input type checkbox thing wrapped in a <div class='ui toggle checkbox'>. Do you know how I would do it for this instead of labe,input? If not I will research as this has given me solid ground to work off of. Thanks!
I bet it is a label. What does console.log(e.target) show when you click on it?

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.