Reputation: 35
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";
}else{
document.getElementById('chap1Completion').innerHTML = "Incomplete";
}
}
</script>
Upvotes: 1
Views: 135
Reputation: 3034
Just concatenate the part of the string before the number with 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";
}
Upvotes: 4
Reputation: 5190
A solution using es6 template string could be this
for (var i = 1; i <=31; i++){
let content = '';
if(localStorage.getItem(`chap${i}Status`) == "1"){
content = "Completed";
}else{
content = "Incomplete";
}
document.getElementById(`chap${i}Completion`).innerHTML = content;
}
Upvotes: 1
Reputation: 803
The following code will work. However, it would be much cleaner for you to just store an Array in local storage, and access it by indexing the array. Also, take a look into using the map
functor over a for loop.
Note also that you should inline the declaration of i
in the for loop as shown below. Otherwise, you may get conflicts with any future use of i
in a for loop.
for (var i = 1; i <=31; i++){
var chapterChecker = localStorage.getItem("chap"+i+"Status");
if(chap1Check == "1"){
document.getElementById('chap'+i+'Completion').innerHTML = "Completed";
}else{
document.getElementById('chap'+i+'Completion').innerHTML = "Incomplete";
}
}
Upvotes: 1