Only the initial value is being processed in the for loop using Javascript

I am having issues trying to sum the values within a for loop sourced from my Django database using JavaScript. Currently, when I iterate through the loop, only the first value in the array is returned. I need assistance in finding a solution that allows all values within the loop to be passed through the script.

   {% for loans in d1_companies %}
        <div id="security-value">{{loans.market_value}}</div>

    {% endfor %}
    <div id="test"></div>                     



     <script>
     for(let i = 0; i < 1000; i++) {
            let sum = document.querySelectorAll(`[id^="test"]`)[i];
            let values = [document.getElementById("security-value").innerText];


            const summed_value = values.reduce((accumulator, currentValue) => accumulator + currentValue);
            sum.innerText = summed_value;

        }

    </script>

Answer №1

It seems unnecessary to loop through 1000 times in this case. Instead, you can select all elements with the class security-value (changed from ids for uniqueness) and iterate over them.

{% for loans in d1_companies %}
  <div class="security-value">{{loans.market_value}}</div>
{& endfor %}

<div id="test"></div>

<script>
  const security_values = Array.from(document.querySelectorAll('.security-value'));
  const security_values_inner = security_values.map((element) => element.innerText);
  const summed_values = security_values_inner.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

  const sum = document.getElementById('test');
  sum.innerText = summed_values;
</script>

Just a friendly reminder: be cautious when using reduce on an element's innerText as it may not always be a number.

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

What are some strategies for accessing the original values of form components that have not been altered when using ngModel?

I am currently developing a form and I intend to utilize the previous values as "value" in the form. By employing ngModel dynamically, I am able to change some properties. However, I have encountered an issue where the field that remains unchanged by the u ...

Javascript 'break' statement is always executed

It seems like I'm overlooking a very basic concept here. Why isn't my code reaching the else statement? The issue might be related to the break statement. It's likely something simple that I am missing. Code Snippet: <button onclick="yo ...

Is there a way to activate the width styling from one class to another?

I have these 2 elements in my webpage: //1st object <span class="ui-slider-handle" tabindex="0" style="left: 15.3153%;"></span> //2nd object <div id="waveform"> <wave style="display: block; position: relative; user-select: none; he ...

I am trying to retrieve the class name of each iframe from within the iframe itself, as each iframe has a unique class name

My index HTML file contains multiple Iframes. I am trying to retrieve the class names of all iframes from inside an iframe. Each iframe has a different class name. If any of the iframes have a class name of 'xyz', I need to trigger a function. I ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

The background color of the columns is overwhelming

I would like to create a TV remote control design using bootstrap, but I am encountering some issues. The background color is overflowing and I'm unsure how to fix it. Please take a look at the code and feel free to offer any suggestions! @media scre ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Is it possible to accept a file as a form-field input in Django without the need to declare it as a Model?

I recently developed a straightforward API for Tax Analysis by processing a ZIP file received from our supplier using the FastAPI framework. However, due to some technical constraints, I have now decided to migrate my APIs to Django. I have been exploring ...

Error in React+Redux: Trying to access the "address" property of a null value is not permitted

I am new to using react and encountering an issue with my ecommerce app. The app runs smoothly until I log out and then log back in at the shipping address page, which triggers the following error: TypeError: Cannot read property 'address' of nu ...

There seems to be a caching issue in ReactJS and Spring Data Rest that could be causing problems with

Encountering an unusual caching problem here. Just recently wiped out my database. While adding new users to the system, an old user mysteriously reappeared. This user has not been recreated and is not in the current database whatsoever. I'm at a lo ...

Is there a way to create a soft light blue backdrop for text using HTML and CSS?

Is there a way to create a light blue background effect behind text using HTML and CSS? You can view the image reference here ...

Using jQuery's setInterval to consistently refresh the value of a data attribute

I am struggling to dynamically update the data-left value of a div with the class name "tw_marquee_scroller" every 1 second. The intended behavior is for the value to increment by 10 each time, starting at 10 and increasing by 10 in subsequent seconds. H ...

Guide on using Ajax and spring MVC to dynamically fill a modal form

One JSP page displays database results in a table on the browser, allowing users to edit or delete each row. I want to implement a feature where clicking the edit link fetches specific customer data from the database using Spring MVC and Hibernate, display ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

Issue with preventDefault not functioning correctly within a Bootstrap popover when trying to submit a

I am facing an issue with a bootstrap popover element containing a form. Even though I use preventDefault() when the form is submitted, it does not actually prevent the submit action. Interestingly, when I replace the popover with a modal, the functional ...

Tips for effectively binding attributes based on conditions in Vue.js

Is it possible to conditionally bind attributes in Vue? Yes, you can achieve this using the v-bind directive: Here is an example: <img :src=" status = true ? 'open.svg' : 'close.svg'"> In Angular, this functionality i ...

The error "500 window is not defined in Nuxt3 when using the composition API"

Is it possible to detect the user's preference for color scheme and set a data-mode attribute on the document root (html)? I've been struggling with this. In my app.vue code, I have the following: <template> <div> <NuxtLayout /> ...

MUI useStyles/createStyles hook dilemma: Inconsistent styling across components, with styles failing to apply to some elements

I have been trying to style my MUI5 react app using the makeStyles and createStyles hooks. The root className is being styled perfectly, but I am facing an issue with styling the logoIcon. Despite multiple attempts to debug the problem, I have not been suc ...

What method does Apple use to apply overflow:hidden to elements within position:fixed?

After conducting my own experiments and delving into the topic online, I discovered that elements using position: fixed do not adhere to the overflow: hidden property of their parent element. This also applies to children within the fixed positioned elemen ...