lundi 12 septembre 2022

Javascript Checkbox - Pushing an Array to Empty Array through click event

I have this mini checkbox feature that I wanted to implement on a web app that I am developing.

The goal is once the user clicked the checkbox particular lesson, it will be added to the vocabulary array.

Here's the code:

const lessonOneEl = document.getElementById("lessonOne");


let vocabulary = [];
const lessonOne = [
    {"ἀγάπη, ἡ": "love"},
    {"γῆ ἡ": "earth, land, ground (geology)"},
    {"ζωή ἡ": "life (zoo, zoology)"},
    {"φωνή, ἡ ": "voice, sound (phonetics, phonograph, phone)"},
    {"ἀλήθεια, ἡ": "truth"},
    {"ἁμαρτία, ἡ":  "sin (hamartiology—the theological study of sin)"},
    {"βασιλεία, ἡ" : "kingdom, reign (basilica)"},
    {"δόξα, ἡ" : "glory, majesty (doxology)"},
    {"ἐκκλησία, ἡ" : "congregation, assembly, church (ecclesiastical)"},
    {"ἡμέρα, ἡ" : "day (ephemeral, “for a day”)"},
    {"καρδία, ἡ":  "heart (cardiologist)"},
    {"δέ" : "and, but, now"},
    {"καί" : "and, even, also"},
    {"μέν" : "on the one hand, indeed"},
    {"ὁ, ἡ, τό" : "the"}
]


const lessonOneEl = document.getElementById("lessonOne");

lessonOneEl.addEventListener('click', () => {
    if(lessonOneEl.checked) {
        console.log("lessons added");
        vocabulary.push(lessonOne);
    }
})
<input type="checkbox" name="lessons" id="lessonOne">
<label for="lessonOne">Lesson 1</label>

For some reason, upon testing, when I clicked on lessonOneEl, it logs "lessons added" but not pushing lessonOne to the vocabulary array.

I wonder what am I missing. I search the web, and I learned different ways to use Javascript checkbox but I can't seem to see what am I missing.

Note: When the code below is outside the event handler, it automatically pushes the lessonOne array to the vocabulary array (which is expected).

vocabulary.push(lessonOne);



Aucun commentaire:

Enregistrer un commentaire