Navigating to an item in the Django framework

I am working on a Django template that generates multiple buttons and aims to toggle the visibility of description text onclick (on the same button in each card):

{% for comida in comidas %}
            {% if comida.slug_food == page.slug  %}
            <div class="food2">
                <div id="food-title">{{comida.titulo}}</div>
                <div id="food-price">{{comida.precio|floatformat:"-1"}}€</div>
                <button class="button" onclick="showDescription(this)">ver+
                <div id="food-description" >
                {{comida.descripcion|safe}}
                </div>
                </button>
                <div id="add-cart">AÑADIR AL PEDIDO</div>

                {% if comida.imagen != null %}
                    <img src="{{comida.imagen.url}}"></img>
                {% endif %}

            </div>

              {% endif %}
        {% endfor %}

where comidas represents a list of strings, and further down in the script block, I've set up:

function showDescription(button){
    var parentDiv = button.parentNode;
    var showText = parentDiv.querySelector("#food-description");
    
    if (showText.style.display === "block"){
        showText.style.display = "none";
    } else {
        showText.style.display = "block";
    }
}

The function currently only toggles the first element due to its implementation. Can someone assist me in making it work for all buttons?

I'm open to suggestions and guidance on how to resolve this issue effectively.

Answer №1

Retrieve unique identifiers using the code {{comida.id}}:

{% for comida in comidas %}

    {% if comida.slug_food == page.slug  %}
    <div class="food2">
        <div id="food-title">{{comida.titulo}}</div>
        <div id="food-price">{{comida.precio|floatformat:"-1"}}€</div>
        <button class="button" onclick="showDescription('{{comida.id}}')">view more
        <div id="food-description-{{comida.id}}" >
        {{comida.descripcion|safe}}
        </div>
        </button>

        <div id="add-cart">ADD TO CART</div>

        {% if comida.imagen != null %}
            <img src="{{comida.imagen.url}}"></img>
        {% endif %}

    </div>
    {% endif %}


{% endfor %}

Here is the accompanying JavaScript:

function showDescription(comidaId){
    var showText = document.getElementById("food-description-" + comidaId);
    if (showText.style.display === "block"){
        showText.style.display = "none";
    } else {
        showText.style.display = "block";
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating the parent tag name within jQuery elements

I am working with an HTML file that consists of around 100 elements. Using jQuery in my JavaScript file, I have created a variable to store all elements present in the HTML document. Additionally, I have another variable specifically for text nodes withi ...

Troubleshooting Heroku Django Gunicorn `Foreman Start` Issue

I've been following the Heroku Django tutorial and I reached the section on 'Using a different WSIG server'. However, when attempting to use gunicorn, I encountered the following error: requirements.txt Django==1.4.1 distribute==0.6.28 dj- ...

What is the purpose of having the same function for onPress in React Native components?

As a beginner in learning react-native, I like to search random projects on GitHub and analyze what seems weird or hard to understand. Today, I came across some code from an unknown individual that looked like this: {isTrue && ( <Touch ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

Having trouble accessing a fully loaded Wordpress remotely through Wamp

After installing WAMP Developer Pro on my Windows 7 computer, a testing website was set up locally. Now, I am trying to test it on the LAN, but when accessing the page, only text appears without any images, themes, or styling. Apache is running on port 80 ...

Working with React to map a multidimensional array containing various keys

Is there a way to map a multidimensional array with different keys? Here's an example array structure similar to what I'm working with (my original array is fetched from an AJAX call and PHP MySQL query): var products = [ { i ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

Using the ternary operator to verify multiple strings

I am encountering an issue with a piece of code that involves checking if the value is null or turnedoff, then inserting a blank space into the variable on the left-hand side. However, I have noticed that the turnedoff value is not being replaced as expect ...

Highchart: precise positioning of ticks on axis

Is there a way to precisely determine the distance or establish an exact distance (in pixels) between two ticks on the x-axis using Highchart? I attempted to use tickPixelInterval, but it doesn't appear to accurately set the distance between two tick ...

Storing an image as an encoded string in MongoDB: Step-by-step guide

Currently, my goal is to transform an image into a string and store it in MongoDB. Additionally, I would like the ability to decode it at a later time. My approach involves solely using Express, MongoDB, and ReactJS. I specifically do not want to upload t ...

The request to delete http://localhost:3000/people/[object%20Object] returned a 404 error, indicating that the resource

I've been attempting to remove a person from my table using the following function: const deletePerson = async (id) => { await fetch(`http://localhost:3000/people/${id}`, { method: "DELETE", headers: { "Cont ...

How can I transfer Gmail message using express rendering parameters?

Using passport-google-oauth for authentication and the node-gmail-api for fetching gmail, I aim to display gmail message after authentication. In order to achieve this, I have written the following code in routes.js: app.get('/profile', isLogged ...

Calculating the factorial of a number using the reduce function

I've been working on a function to find the factorial of an integer and then reducing the array containing factorials (multiplying each element). For instance: factor(5) >>> [1, 2, 3, 4, 5] >>> 1 * 2 * 3 * 4 * 5 >>> 120 v ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

What is the purpose of the Express 4 namespace parameter?

Having worked extensively with Express 4, I recently attempted to implement a namespaced route with a parameter. This would involve routes like: /:username/shows /:username/shows/:showname/episodes I figured this scenario was ideal for express namespacin ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

Uploading data through AJAX without saving it in the database

Can someone please assist me? I am encountering an issue where I am uploading multiple data using an AJAX request. The data appears to upload successfully as I receive a response of 200 OK, but for some reason, the data is not being stored in the database. ...

Mobile page sliding mechanism

My website contains a div that is mostly off the page, but on hover it translates onto the main page. You can check out my website. However, this method doesn't work well on mobile devices. Hovering is not effective and I often have to click multipl ...

What is the main purpose of using the CSS transform:translate() property?

When CSS3 introduced animations with transition properties, it gave developers two main ways to change the position of an element. The first method involves setting the element's position as absolute and adjusting the left, right, top, and bottom prop ...