Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
Javascript Function that shows and hides Div based on Checkboxes Dynamically

So I'm building a form in HTML that makes use of a lot of checkboxes and hidden Divs. Right now I'm using

function HideDiv1() {
  var checkBox = document.getElementById("Check1");
  var div = document.getElementById("Div1");
  
  if (checkBox.checked == true) {
    div.style.display = "block";
  } else {
    div.style.display = "none";
  }
}
<input type="checkbox" id="Check1">CheckBox to show Div1
<div id="Div1" style="display: none;">I should be hidden, assuming the author didn't mess up!</div>

To hide each div based on the appropriate checkbox. But this means that I am copying and rewriting this function every time and the section where I like to keep my functions is getting quite large. I was wondering if there was an easier way to do this such that I would only need one function and I could dynamically show and hide Divs without needing to copy and rewrite this function every time.

(If there is some easy JQuery solution to this: please keep in mind that I have no clue how to use JQuery)

This may be a duplicate, I saw the answer once before in the past but I have no idea how to find it again :(

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use data attributes to identify which div to show when the checkbox is changed.

You can do this by listening for the change event on each checkbox and toggling the corresponding div with jQuery.toggle:

$('input[type=checkbox]').change(function(){
  $('div[data-id='+$(this).data('target')+']').toggle()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>

Vanilla JS implementation:

document.addEventListener('click', function(e){
  if(e.target.matches('input[type=checkbox]')){
    let target = document.querySelector('div[data-id="'+e.target.dataset.target+'"]');
    target.style.display = target.style.display == "none" ? "block" : "none";
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You would add an onchange attribute to the checkbox to call a single function called hideDiv and pass it two arguments that are the ids of the checkbox and the div that you are hiding with that checkbox:

onchange="hideDiv("check1","div1")"

...then hideDiv uses the arguments passed to it to toggle the correct div:

function hideDiv(checkId, divId) {
      const checkbox = document.getElementById(checkId)
      const div = document.getElementById(divId);

      if (checkBox.checked == true) {
          div.style.display = "block";
      } else {
          div.style.display = "none";
  }
}

Get in the habit of using let for variables that you need to change and const for variables that will not change value instead of var.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda