Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • |Toggle| Peter 24-04-1990 A friendly guy 0474657434
  • |Toggle| Martha 22-02-1984 An amazing gal 0478695675
  • |Toggle| William 12-11-1974 An oldie 0478995675

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))
like image 993
Bentley4 Avatar asked Nov 25 '25 18:11

Bentley4


1 Answers

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(); } );
});
like image 134
Adil Avatar answered Nov 28 '25 09:11

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!