Melvin Chua Melvin Chua - 1 year ago 78
Javascript Question

Simplify IF...Else Statement with For Loop [Javascript]

Context: I am creating a table of content to inform user of the page(s) that they have completed/visited.

The if...else statement below is working (by itself) but i want to generate the check for the other 30 chapters using the "i" counter from the FOR loop.

The script will first load the localstorage that contains the value 1 or 0 representing visited / unvisited and transfer that data onto variable chap1check. based on the result, the table of content should then show the user which page have or have not been visited.

im not sure of what i need to do but in theory, i will need to replace all the "chap1..." with the value of "i".

<script type="text/javascript">

var i;
for (i = 1; i <=31; i++){
var chap1Check = localStorage.getItem("chap1Status");

if(chap1Check == "1"){
document.getElementById('chap1Completion').innerHTML = "Completed";
document.getElementById('chap1Completion').innerHTML = "Incomplete";

Answer Source

Just concat the part of the string before the number, followed by the number (i), followed by the part of the string after the number.

for (var i = 1; i <= 31; i ++){
    var chapCheck = localStorage.getItem("chap" + i + "Status");
    document.getElementById('chap' + i + 'Completion').textContent = chapCheck == "1" ? "Completed" : "Incomplete";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download