mercredi 4 mai 2016

jQuery Logic Help: When checkbox is 'checked', slideToggle it's contents. Don't toggle the other checkboxes

I can't get my logic straight! I have 4 checkboxes in divs (called 'bandPackageCheck'), each one that will show different content when clicked (in divs called 'greenBox').

When I click one checkbox, I want it to 'slideToggle' in its respective 'greenBox' div, but have the other ones do nothing (unless they're clicked later on). Then, if the user DOES click another one, I want to keep the previously-clicked ones open as well (unless the user clicks to close them).

I gave the 4 checkboxes IDs, but didn't want to use a different code for each one. How can I do this efficiently?

HTML:

<div class="bandPackageCheck">
    <input type="checkbox" id="checkbox1">
    <label for="trioCheckBox"><span>Checkbox 1</span></label>
</div>    

<div class="greenBox" id="content1">

<div class="bandPackageCheck">
    <input type="checkbox" id="checkbox2">
    <label for="checkbox2"><span>Checkbox 2</span></label>
</div>    

<div class="greenBox" id="content2">

<div class="bandPackageCheck">
    <input type="checkbox" id="checkbox3">
    <label for="checkbox3"><span>Checkbox 3</span></label>
</div>    

<div class="greenBox" id="content3">

<div class="bandPackageCheck">
    <input type="checkbox" id="checkbox4">
    <label for="checkbox4"><span>Checkbox 4</span></label>
</div>    

<div class="greenBox" id="content4">

CSS:

input[type=checkbox]{
    display:none; 
}

input[type=checkbox] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "\f196"; 
    letter-spacing: 10px; 
    color: deepskyblue;
    cursor: pointer;
}

input[type=checkbox]:checked + label:before{
  font-family: FontAwesome;
  display: inline-block;
  content: "\f146"; 
  letter-spacing: 10px; 
  color: deepskyblue;
}

JQUERY:

var checkbox = $(".bandPackageCheck");
var greenBox = $(".greenBox");

$(checkbox).on('change', function(){
    if (this.checked){
        $(greenBox).slideToggle(200);
        $(greenBox).not(this).hide();
    } else {
       $(greenBox).slideToggle(200);
      }
});

Thanks for any advice you can offer! I'm kind of new to jQuery as well, so I may not know the most advanced methods.




Aucun commentaire:

Enregistrer un commentaire