Create Listener for multiple dynamically generated Checkboxes

Asked

Viewed 70 times

1

Problem:

Need to Store the value of multiple Checkboxes that are marked, they are generated dynamically by the API so they do not have a fixed Id, only a value and a "name"

As I am currently doing:

<script>

            let arrayItens = []

            function atualizaArrayItens(value){

                //Se o array já tem o item, retira do array
                if(arrayItens.includes(value)){
                    arrayItens.pop(value)
                    console.log(arrayItens)
                //Se o item não está presente no array, adicione    
                }else{
                    arrayItens.push(value)
                    console.log(arrayItens)
                }

            }

            function enviarDados(){
                //Criar objeto para enviar via POST
                let dadosParaEnviar = {
                    NomeCliente: document.getElementById("nomeCliente").value,
                    ItensComprados: arrayItens
                }
                //Enviar dadosParaEnviar via POST
                console.log(dadosParaEnviar)
            }

        </script>

        <span id="checkBoxes">

            Lista de Compras:<br/><br/>

            Nome do Cliente: <input type="text" id="nomeCliente"><br>

            <input type="checkbox" value="1" onchange="atualizaArrayItens(this.value);">Maçã<br>
            <input type="checkbox" value="2" onchange="atualizaArrayItens(this.value);">Banana<br>
            <input type="checkbox" value="3" onchange="atualizaArrayItens(this.value);">Pêra<br>
            <input type="checkbox" value="4" onchange="atualizaArrayItens(this.value);">Uva<br>

            <input type="button" value="Salvar" onclick="enviarDados();"><br>

</span>

This way the updated functionArrayItens is called each time a checkbox is clicked, there is a more efficient way to perform this task?

  • what you want to do is simply add the atualizaArrayItens(this,value) at an onchange event for all dynamically generated checkboxes?

  • Basically yes, instead of putting ' onchange="updateArrayItens(this.value);"' in every checkbox check everyone that is marked within span and take their value

2 answers

2


Using the selector "#checkBoxes [type=checkbox]:checked" with document.querySelectorAll you will pick up all checkboxes marked. Then making a for...of you add the values in the array, and you can do all this in the function enviarDados(), and does not need the various onchange neither the elements nor two functions:

function enviarDados(){
   
   let arrayItens = []
   let itens = document.querySelectorAll("#checkBoxes [type=checkbox]:checked")

   for(let item of itens) arrayItens.push(item.value)
   
    //Criar objeto para enviar via POST
    let dadosParaEnviar = {
        NomeCliente: document.getElementById("nomeCliente").value,
        ItensComprados: arrayItens
    }
    //Enviar dadosParaEnviar via POST
    console.log(dadosParaEnviar)
}
<span id="checkBoxes">
   Lista de Compras:<br/><br/>
   
   Nome do Cliente: <input type="text" id="nomeCliente"><br>
   
   <input type="checkbox" value="1">Maçã<br>
   <input type="checkbox" value="2">Banana<br>
   <input type="checkbox" value="3">Pêra<br>
   <input type="checkbox" value="4">Uva<br>
   
   <input type="button" value="Salvar" onclick="enviarDados();"><br>
</span>

2

If you want to simply add an event to all your checkboxes, you can use the code below:

var cbs = document.querySelectorAll('#checkBoxes > input[type="checkbox"]');

cbs.forEach(function(cb) {
  cb.addEventListener('change', function() { atualizaArrayItens(this.value) });
})

function atualizaArrayItens(value){
  alert('trigger');
  //substitua isso com a sua função de atualização
}
<span id="checkBoxes">
    Lista de Compras:<br/><br/>

    Nome do Cliente: <input type="text" id="nomeCliente"><br>

    <input type="checkbox" value="1">Maçã<br>
    <input type="checkbox" value="2">Banana<br>
    <input type="checkbox" value="3">Pêra<br>
    <input type="checkbox" value="4">Uva<br>

    <input type="button" value="Salvar" onclick="enviarDados();"><br>
</spam>

I put an Alert in place of the function so you can see working, but just replace the inside of the function and it will work normally, no matter how many checkboxes are created, as long as inside this spam.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.