Search code examples
javascriptjqueryhtmlcssshow-hide

What is an easier way for 'checkbox' to 'show div'?


Currently i am using css, which seemed fine, until i realized i needed alot of these 'checkbox to show div', im assuming there is some beautiful jquery method to do this. https://jsfiddle.net/0qnsvgcw/

<style>
    #part1, #part2 {display: none;} 

    #reveal-part1:checked ~ #part1{display: inline-block;}
    #reveal-part1:checked ~ .qntylabel{margin-right: 0px;}

    #reveal-part2:checked ~ #part2{display: inline-block;}
    #reveal-part2:checked ~ .qntylabel{margin-right: 0px;}
</style>

<html>
<input type="checkbox" id="reveal-part1" class="apple-switch"><span class="qntylabel">10 PIN COMPON</span>
<div id="part1"><input type="text" id="" class="qnty" placeholder="QTY"/></div>
<br>
<input type="checkbox" id="reveal-part2" class="apple-switch"><span class="qntylabel">10 PIN COMPOS</span>
<div id="part2"><input type="text" id="" class="qnty" placeholder="QTY"/></div>
</html>

Solution

  • The best way to do this would still be with CSS. You can make the logic more generic by wrapping each set of elements in a container, such as a div in the following example, then placing common classes on each element which you can then use in the CSS. Try this:

    .part {
      display: none;
    }
    
    .reveal:checked ~ .part {
      display: inline-block;
    }
    
    .reveal:checked ~ .qntylabel {
      margin-right: 0px;
    }
    <div>
      <input type="checkbox" class="apple-switch reveal">
      <span class="qntylabel">10 PIN COMPON</span>
      <div class="part">
        <input type="text" id="" class="qnty" placeholder="QTY" />
      </div>
    </div>
    <div>
      <input type="checkbox" class="apple-switch reveal">
      <span class="qntylabel">10 PIN COMPOS</span>
      <div class="part">
        <input type="text" id="" class="qnty" placeholder="QTY" />
      </div>
    </div>
    <div>
      <input type="checkbox" class="apple-switch reveal">
      <span class="qntylabel">10 PIN COMPOS</span>
      <div class="part">
        <input type="text" id="" class="qnty" placeholder="QTY" />
      </div>
    </div>
    <div>
      <input type="checkbox" class="apple-switch reveal">
      <span class="qntylabel">10 PIN COMPOS</span>
      <div class="part">
        <input type="text" id="" class="qnty" placeholder="QTY" />
      </div>
    </div>