Update div with checkbox value marked

Asked

Viewed 631 times

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 printing checkbox values marked without refresh on the page. It is necessary that the div is also updated when the checkbox is unchecked, deleting the value in the div.

Thank you in advance.

  • What is your doubt?

2 answers

3


If you want div to be updated when you check and uncheck checkboxes you need to use the event change. In this event you have to go through all <input> and put its value if the attribute checked is the 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 MDN change event

  • Thank you very much Isac.

  • @Brunooliveira You’re welcome, I’m glad I could help

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
    }
});
});
  • Could explain what your code is doing to help understanding?

  • Amended with explanation, I apologize if I misunderstood and this is not what you want.

Browser other questions tagged

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