Updating the icon of a dynamically generated element in Javascript and Django depending on the query value or click event

After trying several methods, I finally found a way to change the icon on a button that was generated using a for loop on page load. Below is my element:


{% for i in data %}
    <div class="accordion">
        <div style="margin-left: -10px;">
            <a href="#collapse{{ i }}", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}">
            <i class="material-icons" style="vertical-align: middle;">expand_more</i>
            <label style="vertical-align: middle;">{{ i }}</label>
            </a>
        </div>
    </div>
{% endfor %}

Below is the function I used to change the icon:

<script>
    $(document).ready(function(){
        $('#btn-collapse_{{ i }}').on('click', function () {
            var thisElement = $(this);
            var anchorElement = thisElement.find("i");
            if(anchorElement.text() === "expand_less"){
                anchorElement.text('expand_more');
            } else {
                thisElement.find("i").text("expand_less");
            }
        });
    });
</script>

I also tried changing the color in a different scenario. Here is the element:


<tbody>
{% for i in data %}
    <tr style="vertical-align: middle;">
        <td><a href="#">{{ i }}</a></td>
        <td>{{ i.data1 }}</td>
        <td><a href="#">{{ i.data1 }}</a></td>
        <td style="text-align: center;">
            <button class="btn", id="btn-{{ i.data2 }}">
                <i class="far fa-check-circle"></i>
            </button>
        </td>
        <td style="text-align: center;">
            <button class="btn", id="btn-{{ i.data3 }">
                <i class="far fa-check-circle"></i>
            </button>
        </td>
    </tr>
{% endfor %}
</tbody>

Here is the function used for this:


<script>

    $(document).ready(function(){
        var data_button = document.getElementById("btn-{{ i.data2 }}");
        if({{ i.data2 }} == 'None'){
            data_button.style.color = "#858796";
        } 
        else {
            data_button.style.color = "#1cc88a";

        }
    
    });

</script>

The data queried in the second scenario can either be 'None' or a date.

Answer №1

When writing your script, ensure that {{ i }} is placed outside of the for loop. It's recommended to use class instead of id because selecting elements by class will retrieve all matching elements, while using id only selects the first child. Additionally, there is no need for commas between element attributes.

<a href="#collapse{{ i }}" class="btn" data-id="{{forloop.counter}}" role="button" data-bs-toggle="collapse" id="btn-collapse_{{ i }}">

<script>
    $(document).ready(function(){
        $('.btn').on('click', function () {
            data_id = $(this[data-id])
            var thisElement = $(this).filter('[data-card="'+data_id+'"]');
            var anchorElement = thisElement.find("i");
            if(anchorElement.text() === "expand_less"){
                anchorElement.text('expand_more');
            } else {
                thisElement.find("i").text("expand_less");
            }
        });
    });
</script>

I have utilized jQuery in this solution. Please remember to include it in the head tag of your HTML document.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Answer №2

After making some adjustments to the script provided by enes islam, here is the final version that worked for me:

<a href="#collapse{{ i }}" data-id_collapse="{{ forloop.counter }}" class="btn" role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}">

    <script>
        $(document).ready(function(){
            $('.btn').on('click', function () {
                data_id = $(this).attr('data-id');
                var thisElement = $(this).filter('[data-id=' +data_id+ ']');
                var anchorElement = thisElement.find("i");
                if(anchorElement.text() === "expand_less"){
                    anchorElement.text('expand_more');
                } else {
                    anchorElement.text('expand_less');
                }
            });
        });
    </script>

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

Display a distinct button on the webpage if the logged-in user has not clicked on it yet

Seeking a solution to emphasize buttons that the User has not visited in the event of changes to the content of the views that appear when these buttons are clicked. The answer must utilize the ASP.net MVC CSS framework. <head> <style type="text/ ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Utilize Vue.js to transmit HTTP requests with specified headers and parameters

I'm trying to figure out how to create a LinkedIn login component, but I'm having trouble finding information about headers and parameters. Can someone help me understand how to send a GET or POST request with parameters and headers? Here's ...

What is the purpose of including an express server instance as an argument for the http module in Node.JS?

Currently delving into the realms of Node.JS, Express.JS, and Socket.IO. The tutorials I've come across so far showcase a complex series of code to kickstart each of these modules: var express = require("express"); var app = express(); var server = ...

li experiencing a background width problem due to extended text

Check out this code snippet with a problem In the image below, you can see that the background of the li element with more text is larger compared to the others. It's important to note that the <ul> is scrollable. I've experimented with va ...

Adjust the positioning of elements within a expanded and toggled Bootstrap navbar

Seeking assistance with a responsive Bootstrap navbar design. When the navbar collapses, the "logout" button is not aligning properly. Need help to keep it in the top row on the right side next to the toggler icon or underneath the other items on the right ...

Having trouble retrieving data from a JSON file using JQuery AJAX?

My JSON file structure is presented as follows: { head: { link: [], vars: [ "CompanyName", "Company_Name", "Foundation_URI", "Foundation_Name", "Latitude", "Longitude" ] }, results: { distinct: fal ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

What is the process of transforming an array of date strings into actual dates?

Looking for assistance in converting an array of date strings to actual Date objects. Here is the input data: medicalData = [ { name: 'Allergy', status: 'Normal', testDates: ['2023-07-02T13:21:29.643Z', '20 ...

Switching the chosen option in the <select> element repeatedly

I have successfully set the selected value, but now I am wondering how to keep changing it continuously. Initially, my approach was to remove the "selected" attribute from all options and then add it back to the desired option. Surprisingly, this method w ...

Navigating through the various child objects within a JSON structure

As I traverse through a moderately complex JSON object, I gather and store all the values once I reach the end of the recursive loop Here is an example of the object: "if": { "and": { "or": { "compare": [ { ...

Getting data with a data attribute - a step-by-step guide

I'm attempting to retrieve data from our API using a unique html method involving the data- attribute. I am able to successfully fetch the data directly and load it without any issues. However, when trying to access the data variable from the data att ...

How can data be transferred from child component inputs to a parent form in Angular's template-driven approach?

It seems like this should be a straightforward task, but I'm encountering conflicting instructions on how to achieve it. I have three child components, each with their own set of input controls that are supposed to feed into a parent component. Howeve ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

Define the starting value for Framer Motion's useCycle by taking into account the width of the screen

With the help of Framer Motion's useCycle hook, I am able to toggle the visibility of my sidebar. The desired behavior is to have the sidebar open by default on desktop (window width > 480px) and closed by default on mobile devices. To achieve thi ...

Create a toggle effect using attribute selectors in CSS and JavaScript

I am looking to switch the "fill: #000;" from the CSS property "svg [id^='_']". Usually, I would use a method like this, but it seems that I can't do so because "svg [id^='_']" is not an element, correct? pub.toggleClass = functi ...

What is the best way to fetch a document from a MongoDB database using Mongoose in a Node.js environment

I have been trying to retrieve data from an existing MongoDB model, but all the resources I found demonstrate how to do it with new models. How can I achieve this? const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/a ...

Having trouble with your Ajax post request?

I am currently working on creating a form that allows users to input information and submit it without the page refreshing. The processing of the form data will occur after the user clicks the submit button. To achieve this, I am utilizing jQuery and Ajax ...

Generate a URL link based on the form input when the submit button is clicked

I am aiming to create a feature where a user can input a date to retrieve forecast data from the selected date. The URLs for this function are structured like wwww.mywebsite.com/forecasts/region/{{date}} using Pyramid's URL dispatch. I want users to b ...

Disqus comment box fails to appear on the screen

While going through the instructions provided on Disqus, I encountered an issue where the comment-box failed to render. Everything seemed to be correctly set up from the admin end on Disqus. var disqus_config = function () { this.page.url = {{request.b ...