I am currently utilizing bootstrap for my project. The accordion feature I have implemented is standard, but I am looking for a way to customize its behavior. Specifically, when a user clicks on elements with the class 'option', I want it to select the 'suboptions' without expanding the accordion-item simultaneously, as it currently does. This behavior is quite frustrating to me personally.
In my index.html file, the accordion structure is defined as follows:
<ul class="accordion" id="collection-accordion">
<li class="accordion-item text-center py-3"><h4 class="accordion-header">Collection</h4></li>
<li class="accordion-item">
<h3 class="accordion-header d-flex align-items-center">
<button class="accordion-button collapsed h4 flex-grow-1" type="button" data-bs-toggle="collapse" data-bs-target="#filterCol-1" aria-controls="filterCol-1">
<label class="fs-6 me-2 mb-0">
<input type="checkbox" class="option">
Deep Groove Bearings
</label>
<span class="product-count fw-normal mx-2">(560)</span>
</button>
</h3>
<ul class="accordion-collapse collapse" id="filterCol-1" data-bs-parent="#collection-accordion">
<div class="accordion-body">
<li><label><input type="checkbox" class="subOption">6000 Series<span class="product-count">(450)</span></label></li>
<li><label><input type="checkbox" class="subOption">6200 Series<span class="product-count">(32)</span></label></li>
<li><label><input type="checkbox" class="subOption">6300 Series<span class="product-count">(69)</span></label></li>
</div>
</ul>
</li>
</ul>
For the JavaScript logic in index.js file:
document.querySelectorAll('input.option').forEach(option => {
const subOptions = option.closest('li').querySelectorAll('input.subOption');
option.onclick = function() {
subOptions.forEach(subOption => {
subOption.checked = this.checked;
});
}
subOptions.forEach(subOption => {
subOption.onclick = function() {
const checkedCount = option.closest('li').querySelectorAll('input.subOption:checked').length;
option.checked = checkedCount > 0;
option.indeterminate = checkedCount > 0 && checkedCount < subOptions.length;
}
});
});
I am trying to achieve the behavior where clicking on an option selects the suboptions without affecting the accordion's state of expansion. I have explored various methods, including .stopPropagation(), .preventDefault(), .stopImmediatePropagation, but haven't found a solution yet. I am aiming to maintain the current styling without adding excessive code. Any suggestions on achieving this task efficiently?