herci herci - 1 year ago 81
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 %}
{% endfor %}

And this is the show/hide function:


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

I tried two methods but couldn't be successful:

  1. I added a number to
    divs (with forloop), it becomes:
    , ... 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
    but the
    functions didn't work.

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

Answer Source

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

Then use a traverse to locate associated list

    // "this" is element event occurred on
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download