I'm working on a function that loops over an array (with arrays) and then replaces the text on a few divs with the value of index 1 of the nested arrays.
But only with these conditions:
The function get's activated by an event handler (clicking on 'Categorie 1', see codepen). When clicking on categorie 1, the following values: themaA1 themaA2 themaA3 themaA4 themaA5 themaA6 (each value in a different div) should be visible inside the divs of the green container (see codepen).
Unfortunately I'm not able to get it work.
What does work is looping and putting data in the different divs which shares the same value on index 0. See code below.
function displayThemes() {
let theme = "i";
for (let i = 0; i < forms.length; i++) {
theme = forms[i][1];
if (forms[i][0] === "Categorie 1")
document.getElementById("theme" + i).innerHTML = theme;
}
}
What does not work is getting the right data in the divs (only the unique values).
I got this far (see code below) but it does not work unfortunately.
function displayThemes() {
let theme = "i";
for (let i = 0; i < forms.length; i++) {
theme = forms[i][1];
if (forms[i][0] === "Categorie 1" && forms[i][1] !== theme)
document.getElementById("theme" + i).innerHTML = theme;
}
}
Here is the full code with interface: https://codepen.io/cheizer66/pen/pobXBmy
I'm not sure why it does not work. What am I doing wrong? What should you do differently? What could make it work? I hope I stated the problem clear enough and looking forward to your respons!
Best regards,
OK
ps: Yes, I'm new to javascript and programming 🙃
you had two problems.
first: you assigned forms[i][1]
to theme
variable. and then in the second condition in the if
statment, you checked if it's not equal to theme
, which of course is false. so the code never entered the if
block.
i solved it by assigning it with the previous forms element (or 'check' if the previous element doesn't exist).
second: when you try to catch the element with ID 'theme1' with the ("theme" + i)
expression, i
value is actualy 11 and not 1, because the if
blocked the previous 10 elements with the identical value of index one. so it couldn't find an HTML element with ID theme11
.
i solved it by adding a counter
variable which the code increases by one every time it enter's the if
block;
let counter = -1;
function displayThemes() {
for (let i = 0; i < forms.length; i++) {
let theme = i === 0 ? 'check' : forms[i - 1][1];
if (forms[i][0] === "Categorie 1" && forms[i][1] !== theme) {
counter++;
document.getElementById("theme" + counter).innerHTML = forms[i][1];
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With