I would like that when I check a checkbox, an element is added to the array, and when I uncheck the check box. The code is working, but not properly, and I can’t figure out where it came from.
var tableau= ["0"];
var checkBox_numero = document.getElementById("numero");
checkBox_numero.addEventListener('change', function () {
if (this.checked) {
// Checkbox is checked..
tableau.push("numero");
} else {
// Checkbox is not checked..
tableau.shift();
}
});
console.log(tableau);
You push the numero to your array but you want to delete it with shift, that doesn't works right, because push puts the element at the end and shift takes it from the beinnig away.
So just use pop to take it from the end.
var tableau= ["0"];
var checkBox_numero = document.getElementById("numero");
checkBox_numero.addEventListener('change', function () {
if (this.checked) {
// Checkbox is checked..
tableau.push("numero");
} else {
// Checkbox is not checked..
tableau.pop();
}
console.log(tableau);
});
console.log(tableau);
<input type='checkbox' id='numero'>