Display only one collapse open at a time using Vue 3 and Bootstrap 5

I am currently utilizing Bootstrap5 and Vue 3. In my project, I have several buttons, each of which triggers a different collapse.

My goal is to have only one collapse open at a time, meaning that when I open one collapse, all the others should close. However, at the moment, all collapses remain open simultaneously.

I have attempted to use both data-parent and data-bs-parent, but neither seem to be effective in achieving this desired behavior.

Does anyone know how I can accomplish this? Thank you!

<div class="row margin-top">
  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn color-success" style="height: 200px;" data-bs-toggle="collapse" data-bs-target="#collapse-b1" aria-expanded="false" aria-controls="collapse-b1" data-bs-parent="#myGroup">
        Button 1
      </button>
    </div>
  </div>

  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn color-primary" style="height: 200px;" data-bs-toggle="collapse" data-bs-target="#collapse-b2" aria-expanded="false" aria-controls="collapse-b2" data-bs-parent="#myGroup">
        Button 2
      </button>
    </div>
  </div>
</div>

<div>
  <div class="collapse" id="collapse-b1">
    <div class="mt-3">
      Text 1
    </div>
  </div>

  <div class="collapse" id="collapse-b2">
    <div class="mt-3">
      Text 2
    </div>
  </div>
</div>

Answer №1

To Ensure Proper Functionality, Implement These Minor Adjustments

Your code is almost there but needs a few tweaks to operate smoothly. Make sure to include the

data-bs-parent="#myGroup"
attribute in each collapse element and assign the same id to the parent container housing the collapsible sections.

Keep in mind that in Bootstrap 5, the attribute name has transitioned from data-parent to

data-bs-parent</code. The parent refers to the element containing the collapsible sections and not the container for the toggling buttons and links.</p>
<p>Furthermore, ensure that your buttons have the correct classes applied, such as <code>btn-primary
and btn-success.

For more insights, refer to this relevant Stack Overflow inquiry: Collapse other sections when one is expanded

Execute the provided snippet to observe its functionality:

<div class="row margin-top">
  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn btn-success" style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b1" aria-expanded="false" aria-controls="collapse-b1">
        Button 1
      </button>
    </div>
  </div>

  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn btn-primary" style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b2" aria-expanded="false" aria-controls="collapse-b2">
        Button 2
      </button>
    </div>
  </div>

</div>

<div id="myGroup">  <!-- Assign parent id here -->

  <div class="collapse" id="collapse-b1"  data-bs-parent="#myGroup">
    <div class="alert alert-success mt-3">
      Text 1
    </div>
  </div>

  <div class="collapse" id="collapse-b2" data-bs-parent="#myGroup">
    <div class="alert alert-primary mt-3">
      Text 2
    </div>
  </div>
  
</div>


<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9e9393888f888e9d8cbcc9d2ced2ccd19e99889dcd">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e6c61617a7d7a7a7c6f7e4e3b203c203e236c6b7a6f3f">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

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

Substitute all numerical values with a designated number from a variable

I came across a link that looks like this foo.net/index.php?page=15 My goal is to replace any number after page=xxx and retrieve the new number from a variable Currently, my code only replaces 15 with 16 var num = 16, // What if the str = foo.net/index ...

Displaying Sweetalert2 textarea inputs in an email

How can I capture the user inputs from a textarea in my code? Here are the details: https://i.sstatic.net/trG1E.gif This is my JavaScript code: $('#sad').on('click', function() { const sad = $('#sad').val(); con ...

Tips for handling Google Spanner Date type in JavaScript

I am facing a challenge with Google Cloud Spanner as I work with multiple tables containing columns of type Date. While inserting entries with specified dates works fine, the issue arises when trying to retrieve these entries in the JavaScript frontend. Th ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Tips for sending properties to a Material-UI styled component

I am facing a challenge with passing props to a component that already has internal props for handling styling. I am not sure how to manage both sets of props effectively. Below is my current setup. const styles = theme => ({ // Theme building }); ...

Node is throwing a 302 error on Localhost:3000

Looking for some guidance as a beginner trying to create and run a nodejs application. Encountering an error while running server.js via nodemon, the console displays the following: Express server listening on port 3000 Mongoose default connection open t ...

Starting with NodeJS: Troubleshooting module not found error

I'm new to NodeJS and I'm following the guide on the official NodeJS site to create a server. I have successfully installed NodeJS on my computer and created an app.js file with the code below: const http = require('http'); const host ...

How to Send an Array to AJAX and Retrieve the Data in Codeigniter Controller

I am attempting to retrieve table data, store it in an array, and pass it to the controller so I can write it in PHP Excel. Previously, I had success with other data but now my excel file is turning up empty. Below is the JavaScript code snippet: var Ta ...

The code is throwing an error indicating that an import statement is being used outside of a module specifically in relation

I've been working on building an HTML and JavaScript application that utilizes the jspdf module to export PDF files. However, each time I try to execute the code below, I encounter the error message Uncaught SyntaxError: Cannot use import statement o ...

Is it possible to use a marker with label in conjunction with a google maps circle?

In my mapping project, I use different markers for various scenarios. A regular marker represents an individual item, a customized marker represents a region containing multiple items, and a circle marker is used when there are too many items in one region ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Tomickigrzegorz Script Finder Predictive Search

Hey there, I recently tried out the autocomplete script created by tomickigrzegorz. Check it out here! It's been working smoothly for me, but I'm facing an issue with external link tags like https//google.com not functioning properly. Here is ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Accessing the session object within an Express middleware function is crucial for

This is my unique Express middleware setup: var app = express() .use(express.cookieParser()) .use(express.session({secret: 'HiddenSecret'})) .use(express.bodyParser()) .use(function displaySession(req, res, next) { consol ...

What is the best way to identify a specific AdWords account while utilizing campaignSelector within AdWords scripts?

I have been working on a script that aims to achieve the following tasks: Go through all the accounts in an MCC and pick out the ones with 'SEM' in their name. Go through the campaigns in a selected account and choose those that meet specific c ...

What is the best way to adjust the height of an IFrame to match the size of its content?

I attempted to set the height of an IFrame to 100% (similar to setting a <div> to height:auto). I specified the height attribute in the <iframe> tag as 100% and also set the height in the style to 100%, but it doesn't appear to be functio ...

I can't seem to figure out why my attempts to set a cookie through Express are failing

I am currently facing an issue with sending a cookie back to my React app after logging in. In my server, I have set up a test response: res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end(); In the app ...

How to Link Laravel 5 with Ajax?

I've implemented this Laravel code in my controller for the detach function. $input = Input::all(); $product= Products::findOrFail($input['product_id']); $product->tags()->detach($input['tag_id']); $product= Prod ...

When attempting to insert data into MongoDB with node.js, an issue arises: "TypeError: Unable to access property 'username' of undefined."

I recently set up a MongoDB database and attempted to add data via a POST request using the Postman application. Upon successful creation of the database, a confirmation message was displayed. Here is the code snippet I used: users.js file: const router = ...

The child process is arriving empty, which is causing a requirement

Every time I try to use var childprocess = require('child_process'); I keep getting a blank result. When I attempt var childProcess1 = require('child_process').spawn; it returns as undefined, and, var childProcess2 = require(&a ...