How can I grab a value from a PHP generated div and use Javascript to then change the width of a progress bar HTML5 element?

Viewed 67

What I'm trying to do is add progress bars to several cards I have on a website. I'm using Processwire CMS (which utilizes PHP) to generate my cards and each card has a progress element, a raised amount, and a goal amount like so:

<progress class="progressBar" id="progressbar<?php echo $currentSection; ?>" value="0" max="100"></progress>

<span id="raisedNum<?php echo $count; ?>" class="hidden">
    <?php echo $raised; ?>
</span>

<span id="goalNum<?php echo $count; ?>" class="hidden">
    <?php echo $goal; ?>
</span>

These elements are all wrapped in a loop that generates my cards. I am then trying to grab the values in the id="raisedNum" and "goalNum" spans using Javascript, divide the goal amount by the raised amount, and then insert that number back into the Progress "value" attribute.

Here is the Javascript code I have thus far, that doesn't work:

do {
var count = 0;
var raised = document.getElementById("raisedNum".count);
var goal = document.getElementById("goalNum".count);

raised2 = parseInt(raised);
goal2 = parseInt(goal);
var percent = goal2 / raised2;

document.getElementById("progressbar".count).value += percent;

count++; } while (raised != null);

I'm very new to Javascript and would really appreciate any help to figure this out.

Also, I used a defer attribute on my Javascript import tag but am not sure if I should or not. I imagine that I need the script to run after all of the cards have been loaded so that it can grab the values; however, it still needs to change those values after it does the math and generates the percentage values.

I've looked at similar StackOverflow questions like this: How to get / change value of HTML5 progress bar? but couldn't figure out how to change it to meet my needs.

Thanks in advance for any helpful replies!

2 Answers

You used the . operator from PHP to concat two variables. In JavaScript, you need to use the + operator: var raised = document.getElementById("raisedNum" + count);

If you put a period after any object in JavaScript, it will try to get that property of it. "raisedNum".count would give the count property of the string, but that doesn't exist, so JavaScript wants to get an element by an undefined id, but there's no element with undefined id. Then, you call .value, but it will throw an error because you can't read the value of null.

I actually figured out how to do this entirely using PHP. I was initially having trouble typecasting the strings to integers but after realizing that I could change the field types to integers, didn't need to do any typecasting and was able to quickly create a formula that gave me the percentage from value/raised and insert it into the value attribute of my Progress tag. Thanks you all for all of the responses though!

Related