null
null

Reputation: 3517

jQuery toggle and for each loop woes

I have a page that is loaded via results from db. I'm using the id from the db to give each row on screen a unique identifier.

My structure has a container, each container has the button and div that should be hidden.

<td>
     <div class="ellipsisContainer">
         <button th:id='data-ellipsisBtn- + ${appId}' th:type="button" th:name="ellipsis" th:class="ellipsisBtn">...</button>
         <div th:id='data-ellipsisOptions- + ${appId}' class="ellipsisOptions">
             <span>I should be hidden...</span>
         </div>
     </div>

I've got some parts of the jQuery working but it's getting more and more verbose and that usually means I've done something incorrect, and it's not working how I'd like.

The idea is that all of the <div th:id='data-ellipsisOptions- + ${appId}' class="ellipsisOptions"> divs will be hidden when the page loads, when a user clicks the relevant button it will toggle the show / hide.

So far I have:

//Hide the additional features div
$(document).ready(function() {

    //iterate through all the divs - get their ids, hide them, then call the on click
    $(".ellipsisContainer").each(function() {
        $context = $(this);
        $button = $context.find(".ellipsisBtn");
        // $currentId = $button.attr('id');
        $divOptions = $context.last();

        //$($divOptions).hide();
        $($button).on('click', function(event) {
            $($divOptions).hide();
        });
    });
});

I think there is an issue with the loop as I only seem to be targeting the very last row on the page.

Thanks in advance for any help

Upvotes: 0

Views: 642

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

The problem is you are declaring the variables as global, so in every iteration of the loop you are updating the values of the same variable.

You can just hide the sibling element of the clicked button

$(document).ready(function () {
    //iterate through all the divs - get their ids, hide them, then call the on click
    $(".ellipsisContainer .ellipsisBtn").click(function () {
        $(this).next().hide();

        //if you want to be more specific
        // $(this).siblings('.ellipsisOptions').hide();
    });
});

If you want to make your code work, define the variables as local to the each callback function

//Hide the additional features div
$(document).ready(function () {

    //iterate through all the divs - get their ids, hide them, then call the on click
    $(".ellipsisContainer").each(function () {
        var $context = $(this);
        var $button = $context.find(".ellipsisBtn");
        //            $currentId = $button.attr('id');
        var $divOptions = $context.find('div').last();

        //$($divOptions).hide();
        $($button).on('click', function (event) {
            $($divOptions).hide();
        });
    });
});

Upvotes: 3

Related Questions