mardi 19 avril 2022

jQuery - show and hide div related to different checkbox

Hello I'm fairly new to jQuery (and stackoverflow), i saw a few questions about showing/hiding div for checkbox but i couldn't find a solution that apply for several checkboxes at the same time.

I would like to make it work so that when my first checkbox is checked, the 1st div/panel just after is shown then hiden when uncheck. And the same thing for my second checkbox with its own panel.

Right now, both panel are shown when first checkbox (or second checkbox) is checked. I don't know how to make it so the panel shown or hidden will be dependant of the checkbox (li?).

I would like a solution that could apply without touching the code when adding new checkboxes, so i think maybe ID shouldn't be use, right? is there any solution?

Your help is much appreciated! Thanks in advance!

HTML :

<ul class="form-check-list">
   <li class="js-tabCheck">
     <label for="coupon" class="check">
       <input type="checkbox" id="coupon" class="js-tabCheck-trigger">
       <span class="check__name txt-bold">COUPON</span>
       <span class="txt-notice txt-indent">-50%</span>
     </label>
     <div class="js-tabCheck-panel">
       <p>coupon detail</p>
     </div>
   </li>

   <li class="js-tabCheck">
     <label for="coupon1" class="check">
       <input type="checkbox" id="coupon1" class="js-tabCheck-trigger">
       <span class="check__name txt-bold">COUPON1</span>
       <span class="txt-notice txt-indent">-30%</span>
     </label>
     <div class="js-tabCheck-panel">
       <p>coupon detail</p>
     </div>
   </li>             
</ul>

JQUERY:

$(function(){
  var checkbox = $('.js-tabCheck-trigger'),
  panel = $('.js-tabCheck-panel');

  panel.hide();

  checkbox.change(function(){
    if($(this).is(':checked')){
      panel.show();
    } else {
      panel.hide();
    };
  });

});



Aucun commentaire:

Enregistrer un commentaire