My site shows users their results on a quiz. The results are returned from a SQL database.
I have confirmed that the data is being returned correctly and as the correct type (integer).
The text fields are being added as expected however for the percentage bar (user’s score), only the first one loads correctly.
My code in php file:
$(document).ready(function() {
$width = $("#myResultBar").data('width');
$("#myResultBar").css("width", $width + "%");
});
</script>
My and <?php code that only does the first display with percentage bar correctly:
<?php
for($i = 0; $i < count($life_ins_quiz_chapter_num); $i++){
?>
<!-- results box -->
<div class="result_box">
<h3 class="hd text-center">Chapter: <?php echo $life_ins_quiz_chapter_num[$i];?></h3>
<p><?php echo $life_ins_quiz_chapter_desc[$i];?></p>
<div class="row align-items-center">
<div class="bar_main col-sm-11 col-9">
<div id="mySaving" class="bar">
<div id="mySavingBar" data-width="<?php echo $life_ins_quiz_chapter_pct[$i];?>"></div><!--problem here-->
</div>
</div>
<div class="percent col-sm-1 col-3">
** <!--This only shows up the first time. What am I doing wrong?-->**
<?php echo $life_ins_quiz_chapter_pct[$i]; ?> %
</div>
</div>
<div class="box_analysis">
<h3>Question Score: <?php echo "[ " . $life_ins_quiz_chapter_score[$i] . "/6 ]"; ?> </h3>
<?php //echo $saving_report_detail; ?>
</div>
</div>
<?php
}//end for
?>
I have:
1-Done multiple checks to get the correct data type into that variable gettype(variable) = integer
2-Could not figure out if there was a way to change something in the js to have it increment the id
(for e.g. #MySavingBar_1(2,3)etc..
Open to any guidance or suggestions.
2
Answers
The suggestions from @Chandra Shekhar helped me resolve the issue.
In this case i used the jQuery each() function to iterate through each of the divs that were generated. I had to switch from using id="myResultBar" to a class, class="myResultBar".This was suggested by this answer iterating over divs.... The code that resolved it:
Adjust Code Accordingly
When you are looping through PHP you have multiple
result_box
.so inside the javascript, you need to loop through the
result_box
and set ht progreeswidth
.JS Explanation