herci herci - 1 month ago 9
jQuery Question

How to add jQuery show/hide function inside forloop?

I want to add a jQuery show/hide function to my website. The usual show/hide function works but mine is a bit more complex than the usual one.

The "hide div" and the the div I want to hide/show on click are inside a for-loop and there are tons of divs with this names. I can add specific ids for each div (programmatically) but I couldn't add this name inside JavaScript programmatically: I have to add them manually.

This is the piece of code I want to add the function:

{% for facet in facets %}
<div class="block-title"> {{ facet.name }} <div id="hide">HIDE</div></div>
<ul class="term-list">
{% for stat in stats %}
<li class="term-item>{{ stat.name }}</li>
{% endfor %}
</ul>
{% endfor %}




And this is the show/hide function:

<script>
$(document).ready(function(){
$("#hide").click(function(){
$(".term-list").hide();
});
$("#show").click(function(){
$(".term-list").show();
});
});
</script>




When I click on the hide button, it hides each and every
.term-list
divs as expected.

I tried two methods but couldn't be successful:


  1. I added a number to
    #hide
    and
    .term-list
    divs (with forloop), it becomes:
    #hide1
    and
    .term-list1
    ,
    #hide2
    and
    .term-list2
    , ... But I couldn't add a working for-loop to JavaScript code.

  2. I tried to hide only the following (next)
    .term-list div
    when click to
    #hide
    but the
    next()
    and
    nextAll()
    functions didn't work.





So, what should I do to add jQuery show/hide function inside this for-loop?

Answer

You can't repeat IDs in a page, they are unique by definition. Use classes instead

Then use a traverse to locate associated list

$(".hide").click(function(){
    // "this" is element event occurred on
    $(this).closest('.block-title').next().hide();
});
Comments