vendredi 24 septembre 2021

JS Increment value for each onclick after checking if true

I want to check if all checboxes are checked.

For this, I got this code :

bind() {
    this.checks = document.getElementsByClassName("checkdoc");
    const len = this.checks.length;
    this.validCheckbox = 0;

    for (let i = 0; i < len; i++) {
        this.checks[i].onclick = this.updateValid;
    }

    if (this.validCheckbox === len) {
        this.allChecked = true;
        this.update();
    }
}

updateValid() {
    if (this.checked === true) {
        this.validCheckbox += 1;
    } else {
        this.validCheckbox -= 1;
    }
    console.log(this.validCheckbox);
}

But it don't work because this.validCheckbox is NaN so undefined. If I add it as parameters in this.updateValid like this :

this.updateValid(this.validCheckbox)
...

updateValid(nb) {
    if (this.checked === true) {
        nb += 1;
    } else {
        nb -= 1;
    }
    console.log(nb);
    return nb;
}

First, my console.log give me -1 on the 2nd method, then I can't do multiple calls. If I click on the 1st checkbox, nothing happens because onload, the first call is made. If you got any tips, I'll take it




Aucun commentaire:

Enregistrer un commentaire