Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
change an array depending on whether the checkbox is checked or unchecked using vanilla JavaScript

I am quite new to javascript. Any help very appreciated.

I have created a simplified example for easier explanation. I want to change a finalArray according to whether the checboxes are checked or unchecked.

So for example if friends and strangers checkboxes are checked then the finalArray_ should = ["friend1" ,"friend2", "stranger1", "stranger2"].

If only enemies checkbox is checked then the finalArray_ should = ["enemy1" ,"enemy2"]. And so on.

<body>
    <input type="checkbox" data-id="friends_"> Friends <br />
        <!-- other code and functionality -->
    <input type="checkbox" data-id="enemies_"> Enemies <br />
        <!-- other code and functionality -->
    <input type="checkbox" data-id="strangers_"> Strangers <br />

    <script>
        const friends_ = ["friend1","friend2"];
        const enemies_ = ["enemy1","enemy2"];
        const strangers_ = ["stranger1","stranger2"];
    </script>
</body>

I tried this, but I know it's a crappy solution that doesn't work because I can't concat a string like this.

<script>
    const friends_ = ["friend1", "friend2"];
    const enemies_ = ["enemy1", "enemy2"];
    const strangers_ = ["stranger1", "stranger2"];

    const checkboxes = document.querySelectorAll("input[type=checkbox]");
        checkboxes.forEach(function (checkbox) {
            checkbox.addEventListener('change', function () {
                checked_boxes = Array.from(checkboxes).filter(i => i.checked).map(i => i.dataset.id).join();
                const finalArray = [].concat(checked_boxes);
                console.log(finalArray); //Array [ "friends_,strangers_" ]
            })
        })
</script>

Thanks for your suggestions.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can create a dict using Set and obj of key-value pairs of checkbox data.

When a checkbox is checked then you can toggle its id in dict and then get results by iterating dict

const friends_ = ["friend1", "friend2"];
const enemies_ = ["enemy1", "enemy2"];
const strangers_ = ["stranger1", "stranger2"];

const dict = new Set();
const obj = { friends_, enemies_, strangers_ };

const checkboxes = document.querySelectorAll( "input[type=checkbox]" );
checkboxes.forEach( function ( checkbox ) {
    checkbox.addEventListener( 'change', function (e) {
        const id = e.target.dataset.id;
        if(dict.has(id)) dict.delete(id);
        else dict.add(id);

        const result = [];
        for(let key of dict) result.push(...obj[key])
        console.log(result);
    } )
} )
body {
  display: flex;
}
<input type="checkbox" data-id="friends_" id="Friends" />
<label for="Friends">Friends</label>
<!-- other code and functionality -->
<input type="checkbox" data-id="enemies_" id="Enemies" />
<label for="Enemies">Enemies</label>
<!-- other code and functionality -->
<input type="checkbox" data-id="strangers_" id="Strangers" />
<label for="Strangers">Strangers</label>

about 4 years ago · Juan Pablo Isaza Denunciar

0

I joined the different units into a single object so I can use the data-id as a key to get the array.

I haven't ran it since I made this on my phone, but you can try it and it should work.

ED:

I've changed it on my computer now. Should run and show you the output when clicking the checkboxes.

ED2:

I moved all the logic into a function which is called on pageload and when a checkbox is toggled.

const units = {
  friends_: ["friend1", "friend2"],
  enemies_: ["enemy1", "enemy2"],
  strangers_: ["stranger1", "stranger2"],
}

let selectedUnits = [];

const checkBoxes = document.querySelectorAll("input[type=checkbox]");

checkBoxes.forEach(elm => elm.addEventListener("change", updateUnits));

document.onload = updateUnits();

function updateUnits() {
  selectedUnits = Array.from(checkBoxes)
    .filter(elm => elm.checked)
    .flatMap(elm => units[elm.getAttribute('data-id')]);
  console.clear();
  console.log(selectedUnits);
}
<body>
  <input type="checkbox" data-id="friends_" checked> Friends <br />
  <!-- other code and functionality -->
  <input type="checkbox" data-id="enemies_"> Enemies <br />
  <!-- other code and functionality -->
  <input type="checkbox" data-id="strangers_"> Strangers <br />
</body>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda