Home > other >  Show/hide content on checkbox
Show/hide content on checkbox

Time:12-29

i want to hide all content, i want them to show when checked

like show content when checkbox checked

hide when unchecked so that when i check others they show up too

here is my try but its not working

<style>
#myBike:not(:checked)  #bike {
  display: block !important;
}

#myCar:not(:checked)  #car {
  display: block !important;
}
</style>

<input type="checkbox" id="myBike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="myCar">
<label for="vehicle2"> I have a car</label><br>

<div  id="bike">
  Something for bike
</div>

<div  id="car">
  Something for car
</div>

CodePudding user response:

Please check the code below.

#bike {
  display: none;
}

#myBike:checked~#bike {
  display: block;
}

#car {
  display: none;
}

#myCar:checked~#car {
  display: block;
}
<input type="checkbox" id="myBike" />
<label for="vehicle1">I have a bike</label>
<input type="checkbox" id="myCar" />
<label for="vehicle2">I have a car</label>

<div  id="bike">Something for bike</div>

<div  id="car">Something for car</div>

Expanation:

  1. You have used a wrong syntax ~ vs
  2. By default all div are set as display:block. You should set display:none as its initial.
  • Related