So, I was making a progress bar where it shows the amount of checkboxes checked. But there was an error "Uncaught TypeError: Cannot read property 'checked' of Undefined." I kept trying everything but the error was still there. Here is my JS file:
function updateProgress() {
var i = 0;
var checkAmt = 0;
var checkedAmt = 0;
while (i <= document.getElementsByClassName("gun-check").length) {
if (document.getElementsByClassName("gun-check")[i].checked == "true") {
checkAmt = checkAmt + 1;
}
i = i + 1;
}
document.getElementById("progress-fill").style.width = (100 / 31) * checkAmt + "%";
if ((100 / 31) * checkAmt > 5) {
document.getElementById("progress-text").innerHTML = (100 / 31) * checkAmt + "%";
}
}
Please help!
The problem is that when i
equals document.getElementsByClassName("gun-check").length
, the index will be out of bounds.
Change this line:
while (i <= document.getElementsByClassName("gun-check").length) {
to this:
while (i < document.getElementsByClassName("gun-check").length) {
Also, as @HuyNguyen pointed out in the comments, when checking the boolean value of document.getElementsByClassName("gun-check")[i].checked
, you should be checking it against true
(a boolean), not "true"
(a string).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.