update the div with the checkbox value marked

Asked

Viewed 51 times

1

Let’s cut to the chase, I 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, but would like to know how to make some change so that the input’s within the DIV receive the data instead of the DIV.

  • What name do you want to show? They all have the same name... :/

  • the names are being brought from BD, but to illustrate it would be "Keyboard, Mouse, Phone, Monitor"

1 answer

1


Here is 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. Note that for the example I used type="text" but you can er hidden as you had.

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

  • Got it, Perfect!

  • a question Sergio, if I want to show the sum of the values out of the input I could ?

  • 1

    @Ronaldodelima yes, of course. For this in Vex total.value use the element you want and then .value or .innerHTML if it is an input or other type of element

Browser other questions tagged

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