0

I've got a set of tr tags in a table and some of them have a class of collapsible-parent. When I click on an element in the row it calls this javascript method:

function toggle() {
    $(this).closest("tr").nextUntil(".collapsible-parent").toggleClass("open");
}

But none of the rows inbetween are having the open class added. So the HTML is something like so:

<tr class="collapsible-parent">
    <td>
        <span onclick="toggle()"><i class="fa fa-chevron-circle-right"></i></span>
    </td>
    ...
</tr>
<tr>....</tr>
<tr>....</tr>
<tr class="collapsible-parent">....</tr>

so if I trigger that method on the first tr shown, I'd want the second and third tr to have the open class added to them.

What have I done wrong?

4
  • That would do something different, right? That would walk 'up' the tree until it found one and then just toggle that one. I'm wanting to toll all the sibling tr until I find another one with collapsible-parent Commented Jun 9, 2018 at 21:15
  • 1
    If you are using jQuery, use event listeners instead of calling your functions from html attributes. You're calling it so that this inside of it is undefined. Weren't you getting any error, didn't you do any debugging? Commented Jun 9, 2018 at 21:18
  • No, there are no errors printed in the console when that runs. Commented Jun 9, 2018 at 21:27
  • 1
    OK, I switched to using a class on the span and an event listener like you suggested and now it's working. Thanks! Commented Jun 9, 2018 at 21:38

1 Answer 1

1

I just now realised that you have fixed your problem, though I will keep the answer for future reference as it is a tricky bug.

The onclick event listener is not captured correctly by jQuery. I have managed to run this successfully by adding an id on the span element and then adding an .on("click") listener using jQuery.

Add an id on the span element:

<span id="btn"><i class="fa fa-chevron-circle-right"></i></span>

and add a listener using jQuery:

$("#btn").on("click", function() {
    $(this).closest("tr").nextUntil(".collapsible-parent").toggleClass("open");
});
Sign up to request clarification or add additional context in comments.

Comments

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.