Tips for stopping an accordion from toggling in Bootstrap when a user clicks on a specific section of the toggle button

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">&#40;560&#41;</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">&#40;450&#41;</span></label></li>
        <li><label><input type="checkbox" class="subOption">6200 Series<span class="product-count">&#40;32&#41;</span></label></li>
        <li><label><input type="checkbox" class="subOption">6300 Series<span class="product-count">&#40;69&#41;</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?

Answer №1

To make things simpler, remove the input from the button trigger.

<h3 class="accordion-header d-flex align-items-center">
  <input type="checkbox" class="option" />
  <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"> Deep Groove Bearings </label>
    <span class="product-count fw-normal mx-2">&#40;560&#41;</span>
  </button>
</h3>

However, if the input must remain within the button for any specific requirement, then you will need to

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap 3 with a left sidebar menu featuring subtle ghosting borders for a sleek and modern

Hello there! I have a bootstrap 3 sidebar that seems to be causing some issues in IE 11. Specifically, I am encountering a strange ghosting effect on the border of the sidebar. When the page initially loads, only the bottom edge of the sidebar is visible. ...

Angular 4: Implementing a Re-login Dialog/Modal Using Interceptors

Issue Description I recently started working with Angular 4 and I am facing a challenge in handling user re-logging when the token expires. Let's Dive Into the Code I have implemented a response intercepter that checks for a 401 error in the respon ...

Executing a sequence of jQuery's $.when().then() functions

I am facing challenges in understanding how to properly sequence my functions, especially in relation to the $.when() method. function y() { defer = $.Deferred(); $.when(defer).then(console.log(defer.state())); } y(); <script src="https://ajax.go ...

Developing a progress bar with jQuery and Cascading Style Sheets (

Below is the code I'm currently using: <progress id="amount" value="0" max="100"></progress> Here is the JavaScript snippet I have implemented: <script> for (var i = 0; i < 240; i++) { setTimeout(function () { // this repre ...

What is the reason for not allowing return statements in the ternary operator?

Imagine you have a basic form and you want to determine if the form has been modified. If it has changed, you want to submit it; otherwise, you want to prevent form submission. To tackle this, instead of using an if-else statement, I decided to go for a te ...

Is there a way to prevent my jQuery from triggering the <a href> unless the ajax post is successful?

I am attempting to update the database and redirect the user's browser to a new page with just one click. Here is how the HTML appears: <a id='updateLiveProgress' style='width:118px;' href='~link~'>Click here</ ...

Launching a segment from a different page within a foundation reveal modal

With the goal of displaying a modal that contains content from a section on another page when a link is clicked, I encountered a specific issue. For instance: <a href="/otherpage" data-reveal-id="myModal" data-reveal-ajax="true"> Click Me For A Mod ...

What is the best way to ensure that the text within Span children is properly laid out to match the width of the parent div tag?

This particular instance involves setting the width of the div tag to 200px and organizing all the span children to occupy the entire width of the parent div tag. If the first row is filled, the span tags should then flow into a second row. My attempt at ...

JavaScript truthy values referring to numbers

According to the rules outlined below: Falsy: false 0 (zero) '' or "" (empty string) null undefinded NaN (e.g. the result of 1/0) Truthy: Anything else I'm puzzled as to why, in the tests that follow, only the number 1 is considered "tr ...

What is the best way to create a triangle-shaped div using CSS styling?

Seeking assistance in creating a triangular shape using CSS within a rectangular division. Grateful for any guidance provided. ...

Problems persist with storing Node.js values in database

I need help inserting values from a socket emit into my database. Here is the code I am using: socket.on("chat message", (data) => { var sql = "INSERT INTO tbl_user_chats (sender,receiver,message,created_at,ad_id,category_id) VALU ...

Is there a way to eliminate the gap between my menu choices?

Is there a way to eliminate the black line that appears between my menu options when using CSS hover? https://jsfiddle.net/jameskelly/3ejsu7gx/2/ a:hover { background-color: #ebebeb; font-color: black; } /* Custom styling for the ...

Effective ways to position images within a card alongside a changing title

I have a requirement for displaying multiple cards with dynamic titles fetched from the backend. The challenge is to align images in a row regardless of the title length, ensuring alignment based on the longest title. Below is an illustration of what I am ...

Identifying the Operating System of Your Device: iOS, Android or Desktop

I am in need of displaying different app download links based on the user's operating system. This includes IOS, Android, or both if the user is accessing the page on a Desktop device. I am currently utilizing React and Next.js for this project. Unfor ...

Ways to eliminate gaps between div elements with CSS

I am currently working on a webpage that consists of one main div housing two inner divs (left_menu and content), along with an additional footer div outside the main container. When viewing the page, there seems to be a noticeable gap between the footer ...

Troubleshooting problem with updating a record in the MongoDB using Node.js and

Currently, I am developing a REST API using Node, Express, and MongoDB. I have successfully implemented fetch, create, and delete functions but facing issues with the update function. Every time I attempt to test it using Postman, the code hangs, the serve ...

Avoiding a browser becoming frozen during an AJAX call

I'm currently working on sending a request when a user closes the page using the onbeforeunload event. This event triggers when the tab is closed or the page is refreshed. Here's my event implementation: window.onbeforeunload = function() { ...

Error arises when using ODBC PDO alongside Ajax functionality

I've encountered a problem while working on a project at my job. I'm using PDO queries and ajax to generate dynamic elements, but I can't seem to fix a specific issue. The problem is that regardless of the option selected in two dynamically ...

Attempting to create a pathway for removing a profile and user from mongoDB

Hello, StackOverflow community! This is my initial post here and I'm excited to seek guidance. I recently created a delete route in Express to delete both a user and their profile: // @route DELETE api/profile/ // @desc Delete user and profile / ...

Ways to avoid the CSS on the page impacting my widget?

Currently working on a widget using JavaScript and avoiding the use of iframes. Seeking assistance on how to prevent the styles of the page from affecting my widget. Initially attempted building it with shadow DOM, but ran into compatibility issues with ...