Refresh div with checked checkbox value

2

I have these checkboxes on my page

<input type="checkbox" name="dezenas[]" value="01" />
<input type="checkbox" name="dezenas[]" value="02" />
<input type="checkbox" name="dezenas[]" value="03" />
<input type="checkbox" name="dezenas[]" value="04" />

I need a function to update a div by printing the values of checkboxes marked with no refresh on the page. It is necessary that the div be updated also when the checkbox is unchecked, deleting the value in the div.

Thank you in advance.

    
asked by anonymous 03.11.2017 / 15:37

2 answers

3

If you want the div to be updated when you check and uncheck the checkbox's you need to use the change event. In this event you have to go through all <input> and set its value if the checked attribute is true .

Example:

const inputs = [...document.querySelectorAll("input[name='dezenas[]']")];
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="dezenas[]" value="01" />
<input type="checkbox" name="dezenas[]" value="02" />
<input type="checkbox" name="dezenas[]" value="03" />
<input type="checkbox" name="dezenas[]" value="04" />

<div id="resultado"></div>

Documentation for the change event in MDN

    
03.11.2017 / 16:09
0

With jquery:

$( "input:checkbox" ).on('click', function() { // evento click para inputs checkbox
$('#myDivId').html(''); // limpa div
$( "input:checkbox" ).each(function () { // percorrer inputs checkbox
    if ($(this).is(':checked')) { // se checked
        $('#myDivId').append($(this).val()); // adiciona valor a div
    }
});
});
    
03.11.2017 / 16:09