Invoking a JavaScript function from iterated elements when the page loads

Hey there, I'm looking to make my progress bars dynamic using Javascript. I am currently working with Django and a Postgres DB. So far, I've been able to style them with a JS function, but now I want this function to trigger when the page loads.

In the view, I can pass the number of votes for each poll_product object and the total number of votes. I want to send these values as arguments to my JS function so that I can calculate the percentage and set it accordingly.

I hope that explanation was clear enough, but feel free to ask if you need more details.

            {% for poll_product in poll_product_list %}
                <form action="{% url 'add_vote' poll_product.id %}" method="POST">
                    {% csrf_token %}
                    <div class="row mt-1">
                        <div class="col-8">
                            <h5>{{ poll_product.product_type }} : {{ poll_product.votes }}</h5>
                        </div>
                        <div class="col-4">
                            {% if user.is_authenticated and not voted %}
                                <input type="submit" class="btn-sm btn-dark" value="Vote">
                            {% endif%}
                        </div>
/* ------------ below is the relevant part ---------------- */
                        <div class="col-6 progress">
                            <div id="{{poll_product.id}}" class="progress-bar" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" ></div>
                            <script>setProgressBar('{{poll_product.votes}}', '{{total_votes}}', '{{poll_product.id}}');</script>
                        </div>
                    </div>
                    <input type="hidden" name="redirect_url" value="{{ request.path }}">
                </form>
            {% endfor %}

Answer №1

After some troubleshooting, I managed to resolve the issue by utilizing the following JavaScript function:

function updateProgressBar(votesCount, totalVotesCount, productIdentifier) {
    let completionPercentage = Math.round((votesCount / totalVotesCount) * 100);
    document.getElementById(productIdentifier).style.width = completionPercentage + "%";
} 

Adjusted the original code to include the function call within the HTML structure.

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

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Modifying state through inter-component communication in React.js

I need to implement a mechanism where the state of the main component can be updated from the "A" component, then passed to the "B" component for rendering and populating boxes dynamically. Main Component : constructor() { super(); this.s ...

Contrast arrays and eliminate values that do not match

$scope.territories = [ { name : "One"}, { name : "Two"}, { name : "Three"}, { name : "India"}, { name : "Japan"}, { name : "China"} ]; $scope.tempTerritories = [ { name : "One"}, { name : "Two"}, { name : "global"}, ]; ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

I'm encountering an issue with my React 18 application using TypeScript: the module './App' cannot be found

Encountering an issue while attempting to update to react 18. I'm curious if this problem is related to my file types. I am using Typescript, so do both the app and index files need to have a .tsx extension? Both the app and index files are located ...

React - Stopping the Submit Action

Recently, I have been delving into React development. In my exploration, I have incorporated the Reactstrap framework into my project. However, I have encountered an issue where the HTML form submits when a button is clicked. Is there a way to prevent this ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

The webpage encountered an error while attempting to load a resource: server reported a 404 (Not Found) status for jquery-1.7.1.min.js

I am currently in the process of creating an asp.net web application. For my project, I have included jquery-1.7.1.min.js using the code snippet below: <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> However, upon testing, ...

The issue of Ajax response not triggering the ng-click function

When attempting to pass data through an AJAX return, I encountered an issue with a function that writes an ng-click in Angular 1. The code snippet is as follows: $.ajax({ 'method': 'GET', 'url': base_url +&apos ...

Tips for effectively submitting a form to Flask using AJAX

As someone who is new to Python and AJAX, I have encountered an issue with my app.py and app.html files. Instead of displaying the desired result, a whole form is replacing it. Can anyone help me with this problem? Below is the code snippet: from flask i ...

Mastering the art of invoking the right view method in Django

I currently have a project structure with the following files and folders: ... old project new common manage.py ... To access the "old" section, I use the link . Inside this folder, there are views, form urls, etc., which all function properly. Similarl ...

Python framework, Django encountering issue connecting to MySQL database

Initially, I was able to successfully connect MySQL in .py using the following code: import pymysql db = pymysql.connect(host='localhost',user='root',passwd='admin',port=3306) cursor = db.cursor() cursor.execute("SELECT VERSI ...

Saving user-generated inputs within a React.js component's state, focusing on securely handling passwords

Curious about forms in React.js? I don't have any issues, but I'm wondering if there are potential flaws in my approach. I've set up a basic form with two inputs for email and password: <input type="email" name="email" value= ...

Enhancing User Experience with React Hover Effects

I'm currently in the process of developing a React component library, and I'm looking to enhance the components with some stylish flair. Everything seems to be working smoothly, but I'm interested in changing the background color when a user ...

Passing PHP Variables Between Pages

I'm currently working on building a game using html5(phaser js) and I need to create a leaderboard. Here's the code snippet I have: restart_game: function() { // Start the 'main' state, which restarts the game //this.game.time.events ...

Adding model ImageField Upload using DjangoREST and Angular

I'm new to REST and I am trying to create a simple app with one model that has two fields: CharField and ImageField. model: class Photo(models.Model): img = models.ImageField(upload_to='photos/', max_length=254) text = models.CharF ...

Update data in the datatables using values from an array list

Currently, I have two HTML files where I am loading data using JSON and then applying jQuery datatables to them. Now, I need to refresh the data with new parameters. For example: JSON: [ {"name":"jon","sales":"100","set":"SET1"}, {"name":"charlie","sale ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...

Incorporate a button within a listview on Kendoui to trigger the opening of a modal window

I am seeking assistance on how to insert a button on each element of a Listview (PHP/Json) result. When clicked, this button should open a modal window where the customer can input reservation details such as Date, Adults, and Children. Below is the JavaSc ...

The javascript function in my file isn't being triggered by jquery

In my ASP.NET MVC project, I am facing an issue with a jQuery function in a JavaScript file located under the Scripts folder. This function is supposed to fill a textbox with the selected value upon clicking a dropdown, but for some reason it is not workin ...