update the div with the checked-in checkbox value

1

Let's get right to the subject, thank you in advance.

const inputs = [...document.querySelectorAll("input[name='nomes[]']")];
const res = document.getElementById("resultado");

inputs.forEach(x => x.addEventListener("change", ()=> {
  //esta função corre quando houve alteração de um dos checkboxes
  res.innerHTML = ""; //limpar o resultado

  //passar em todos os inputs e adicionar o seu value e <br> se tiver checked
  inputs.forEach (y => res.innerHTML += y.checked ? y.value + "<br>" : "");
}));
<input type="checkbox" name="nomes[]" value="01" />
<input type="checkbox" name="nomes[]" value="02" />
<input type="checkbox" name="nomes[]" value="03" />
<input type="checkbox" name="nomes[]" value="04" />

<div id="resultado">
  <input type="hidden" name="total" value="seria a soma dos valores">
  <input type="hidden" name="nomes" value="seria os nomes[] marcados(A,B,C..)">
</div>

The code is working as it should, however I would like to know how to make some changes so that the input's within the DIV receive the data instead of the DIV.

    
asked by anonymous 30.11.2018 / 16:20

1 answer

1

Here's a suggestion:

const inputs = [...document.querySelectorAll("input[type='checkbox']")];
const res = document.getElementById("resultado");
const total = res.querySelector('[name="total"]');
const nomes = res.querySelector('[name="nomes"]');


const calcular = () => {
  total.value = inputs.filter(el => el.checked).reduce((sum, el) => sum + Number(el.value), 0);
  nomes.value = inputs.filter(el => el.checked).map(el => el.name).join(',');
};

inputs.forEach(x => x.addEventListener("change", calcular));
<input type="checkbox" name="Teclado" value="01" />
<input type="checkbox" name="Mouse" value="02" />
<input type="checkbox" name="Fone" value="03" />
<input type="checkbox" name="Monitor" value="04" />

<div id="resultado">
  <input type="text" name="total" value="seria a soma dos valores">
  <input type="text" name="nomes" value="seria os nomes[] marcados(A,B,C..)">
</div>

The idea is to modify the .value of the destination input. Notice that for the example I used type="text" but you can hidden as you had.

So, using .name with a .filter before and .join(',') you create the name string; using a reducer with a .filter before you make the sum.

    
30.11.2018 / 16:28