Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery with Jinja2 to provide onclick event inside a loop on each element

Tags:

jquery

jinja2

So first off im fairly new to programming in general and definetley new to Jinja2. So I am using python with GAE for server side stuff. I am basically getting some data from the web and then parsing through it and displaying it on a web page. To display it correctly I am looping through the different elements using jinja2.

{% for new in news %}
    <div>{{new}}</div>
    <button id = "button"></button>
    <div id ="description"> {{new.description}}</div>
{% endfor %}

The description part is hidden until it is clicked on by the user

$(#button).each(function(){
    $(this).click(function(){
      $(description).toggle();
    });

});

This html is a seperate page that is getting Ajaxed in to my main html page. So basically I dont know how to select each element in the loop to show there individual descriptions. Using the .each() function in Jquery seemed like a good place to start but it wasnt working properly. Is there someway to change the div id to be something different each time it loops through like adding a number to it or something to make each one distinct? Thanks in advance for any help

like image 400
David Avatar asked Nov 16 '12 20:11

David


1 Answers

I'm doing something similar.

As you probably know by now, variables set outside of loops in Jinja2 cannot be operated on within the loop. The scope of Jinja2 is a little confusing at times, but I suspect this is deliberate to attempt to keep too much logic out of the template.

Anyway, I have an id value for each of my news entries.

{% for entry in news %}
    <div>{{entry.subject}}</div>
    <button id="button_{{entry.id}}" class="clickme">Click Me!</button>
    <div id="description_button_{{entry.id}}">{{entry.description}}</div>
{% endfor %}

Keep in mind that HTML ids should be unique. For the jQuery, something like:

$('.button').each(function(){
    $(this).click(function(){
        $('#description_'+$(this).attr('id')).toggle();
    });
});

What that does is it takes the button's ID value and appends it to the ID selector of the description div.

Edit, here's a working example: http://jsfiddle.net/VQKee/

like image 78
Aaron Meier Avatar answered Nov 15 '22 03:11

Aaron Meier