I am trying to sum the values in a for loop from my django database. Whenever I pass the loop through javascript, it only returns the first value in the array. I was wondering if someone could help me figure out how to get all the values in the loop to pass 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>
CodePudding user response:
I'm not sure why you're looping through 1000 times. You can grab all instances of security-value
(which I've changed into classes because as @Pointy mentioned, ids need to be unique), and loop through them.
{% for loans in d1_companies %}
<div >{{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>
As an aside, be careful reducing over an element's innerText
and blindly assume that it's a number. It could be, or it could be something else.