Bentley4
Bentley4

Reputation: 11038

Jquery toggle (visible/invisible) for only the item clicked on in a template-generated html list

Code

  <ul>
    {% for item in lis %}
    <li>
      <div id="single-toggle">|Toggle|</div>
      <div class="visible-when-folded">
        <div class="name">{{ item.name }}</div>
        <div class="date">{{ item.date }}</div>
      </div>

      <div class="invisible-when-folded">
        <div class="about">{{ item.about }}</div>
        <div class="contact_info">{{ item.contact_info }}</div>
      </div>
    </li>
    {% endfor %}
  </ul>

Example output code

Desired behavior

I would like that whenever you click on |Toggle| the about(e.g. A friendly guy) and contact_info(e.g. 0474657434) part dissapear/reappear.

Attempt at solution

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded").toggle(); } );
});

But unfortunately this toggles the fields for each item in the list as opposed to only the one I click on.

Edit

views.py

from django.shortcuts import render_to_response
from django.template import RequestContext

def toggle(request):
    lis = [{'name':'Peter', 'date':'24-04-1990', 'about':'A friendly guy',
            'contact_info':'0474657434' }, 
          {'name':'Martha', 'date':'22-02-1984', 'about':'An amazing gal', 
            'contact_info':'0478695675' },
          {'name':'William', 'date':'12-11-1974', 'about':'An oldie', 
            'contact_info':'0478995675' }]

    return render_to_response('page.html', {'lis':lis},
      context_instance=RequestContext(request))

Upvotes: 3

Views: 1199

Answers (2)

Dwayne
Dwayne

Reputation: 1

You need to focus the function on the div within the clicked div... The actual code you need to use is:

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded", this).toggle(); } );
});

Upvotes: 0

Adil
Adil

Reputation: 148150

You need to pass the current object as context in the selector to get the element related to event source object. You also need to use class instead of id or generate unique ids for div with id = single-toggle as html elements are supposed to have unique ids.

Live Demo

I have give the div with id a class="single-toggle"

Change

$("div.invisible-when-folded").toggle();

To

$("div.invisible-when-folded", this).toggle();

You code

$(function(){
  $("#single-toggle").click(
    function(){ $("div.invisible-when-folded", this).toggle(); } );
});

Upvotes: 1

Related Questions