Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda