RwitamB RwitamB - 2 months ago 25
HTML Question

Bootstrap Accordion Toggle On Off

I have a Bootstrap accordion written on my webpage, which works absolutely fine.
I wanted to write some added functionality, using Bootstrap Toggle ( http://www.bootstraptoggle.com ).

The main idea is that, when a checkbox is ticked, the accordion feature will work ( only one panel open at a time), and when the checkbox is unticked, we can open multiple panels at once.

Since the accordion feature works using the "data-parent" set to the "panel-group" div, I tried changing the id of the div to disable accordion, but it doesn't really work.


This is the div for the panel group.(Have 2 of them)

<div name="panel1" class="panel-group" id="blah">


Checkbox


<div align="center" class="checkbox">
<input onchange="setClass(this)" id="collapse-logic" type="checkbox" data-toggle="toggle" data-on="Shrink On" data-off="Shrink Off">
</div>


This is the JS code on the onchange() event for my checkbox

function setClass(elem){
if(elem.checked){
document.getElementsByName("panel1")[0].id="accordion";
document.getElementsByName("panel2")[0].id="accordion2";
}
else{
document.getElementsByName("panel1")[0].id="blah";
document.getElementsByName("panel2")[0].id="blah2";
}
}




I figured changing the data-parent name will disable the functionality, but it doesn't quite work. Where am I going wrong ?

Answer

You need to "destroy" the collapse plugin and then re-init without the parent option..

   // multi mode
   $('.panel-collapse').removeData('bs.collapse'); // destroy collapse
   $('.panel-collapse').collapse({parent:false});

   // single accordion mode
   $('.panel-collapse').removeData('bs.collapse'); // destroy collapse
   $('.panel-collapse').collapse({parent:'#accordion'}); 

Codeply Demo