简体   繁体   中英

How to add an element to an array when a checkbox is checked

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'>

Basically, you have [“0”] as the first element in the array. Then you push numero to the array, so it looks like this: [“0”, numero].

Then when you call shift: it removes the first element, which is “0”.

The best way would be to find and remove that checkbox from the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM