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?– Máttheus Spoo
Basically yes, instead of putting ' onchange="updateArrayItens(this.value);"' in every checkbox check everyone that is marked within span and take their value
– Luis Fernando Consulo Martins