Guidelines for creating a dynamic Bootstrap 4 accordion with Jquery

I need help adding a new Bootstrap 4 accordion when a button is clicked. Can someone assist me with implementing this feature in jQuery? I'm not sure if it's possible to add accordions dynamically using jQuery.

 <script>
  $(document).ready(function(){
    $('#addAccordion').click( function() {
        var newDiv = "<div class='card'> <div class='card-header'> <a class='card-link' data-toggle='collapse' href='#collapseOne'>
        Collapsible Group Item #1</a>
        </div>
      <div id='collapseOne' class='collapse show' data-parent='#accordion'>
        <div class='card-body'>Lorem ipsum dolor sit amet,</div> </div> </div>";
        $('.display').append(newDiv);
           
    });
    });
</script>
<div id="accordion">
    <div class="card">
      <div class="card-header">
        <a class="card-link" data-toggle="collapse" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </div>
      <div id="collapseOne" class="collapse show" data-parent="#accordion">
        <div class="card-body">
          Lorem ipsum dolor sit amet, 
        </div>
      </div>
    </div>
    
    
  </div>
  
    <div class="display"> </div>
    
     <button id="addAccordion">Add new accordion</button>

Answer №1

You have the ability to incorporate dynamic accordion functionality, allowing you to open and close accordions dynamically.

let id = 0
$('#addAccordion').click(() => {
id++
       var newAccordion = "<div class='card'> <div class='card-header'> <a class='card-link' data-toggle='collapse' href='#collapse"+id+"'>" +
         "Collapsible Group Item "+id+"</a> </div> <div id='collapse"+id+"' class = 'collapse' data-parent = '#accordion' ><div class='card-body'> Lorem ipsum dolor sit amet, </div> </div> </div>";
       $('.display').append(newAccordion);
     });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div id="accordion">
    <div class="card">
      <div class="card-header">
        <a class="card-link" data-toggle="collapse" href="#collapseOne">
          Collapsible Group Item #1
        </a>
      </div>
      <div id="collapseOne" class="collapse show" data-parent="#accordion">
        <div class="card-body">
          Lorem ipsum dolor sit amet, 
        </div>
      </div>
    </div>
    <div class="card">
      <div class="card-header">
        <a class="collapsed card-link" data-toggle="collapse" href="#collapseTwo">
        Collapsible Group Item #2
      </a>
      </div>
      <div id="collapseTwo" class="collapse" data-parent="#accordion">
        <div class="card-body">
          consectetur adipisicing 
        </div>
      </div>
    </div>
    
  </div>
  
    <div class="display"> </div>
    
     <button id="addAccordion" type="button">Add new accordion</button>

If you find this solution helpful, please consider voting for it as useful. Thank you!

Answer №2

To correct the syntax error, all you need to do is use backtick instead of inverted comma while defining var newDiv

Working Code:-

$(document).ready(function(){
              $('#addAccordion').click( function() {
                  var newDiv = `<div class='card'> <div class='card-header'> <a class='card-link' data-toggle='collapse' href='#collapseOne'>
                  Collapsible Group Item #1</a>
                  </div>
                <div id='collapseOne' class='collapse show' data-parent='#accordion'>
                  <div class='card-body'>Lorem ipsum dolor sit amet,</div> </div> </div>`;
                  $('.display').append(newDiv);
              });
              });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

 <div id="accordion">
        <div class="card">
          <div class="card-header">
            <a class="card-link" data-toggle="collapse" href="#collapseOne">
              Collapsible Group Item #1
            </a>
          </div>
          <div id="collapseOne" class="collapse show" data-parent="#accordion">
            <div class="card-body">
              Lorem ipsum dolor sit amet, 
            </div>
          </div>
        </div>
        <div class="card">
          <div class="card-header">
            <a class="collapsed card-link" data-toggle="collapse" href="#collapseTwo">
            Collapsible Group Item #2
          </a>
          </div>
          <div id="collapseTwo" class="collapse" data-parent="#accordion">
            <div class="card-body">
              consectetur adipisicing 
            </div>
          </div>
        </div>
        
      </div>
      
        <div class="display"> </div>
        
         <button id="addAccordion">Add new accordion</button>

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

What is the best way to retrieve seat number upon clicking in React Native?

I have implemented a for loop and assigned its value in the click function to retrieve the seat number when a seat is clicked. However, I am only getting the last number of the for loop every time a seat is clicked. Can someone guide me on how to obtain th ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

Error code 1 encountered an internal error while trying to execute a task

Currently, I have this job set up to clear out unnecessary records. The code provided has been simplified for debugging purposes. However, almost 80% of the time when running it, it fails to find anything due to Error code 1 "internal error": Parse.Cloud. ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Ways to add a value to an Array within the State

Currently in the process of developing a form for creating blog posts that requires an input field with the name tags, which is meant to be an array in the state. To populate the array, I am utilizing the .push method to add my inputs to an initially empt ...

Find out if OpenAI's chat completion feature will trigger a function call or generate a message

In my NestJS application, I have integrated a chat feature that utilizes the openai createChatCompletion API to produce responses based on user input and send them back to the client in real-time. Now, with the introduction of function calls in the openai ...

Animating a jQuery Knob as you scroll from 0 to a set value

I am new to jQuery and currently working on jQuery Knob. Everything is functioning properly, but I have encountered an issue. When scrolling to the section with the knobs, I would like them to animate from 0 to a specific value. Is there a way to achieve ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Tips for retrieving text without a class or id using selenium and python

I am attempting to extract a list of variables (date, size, medium, etc.) from the following webpage using python/selenium: Getting the titles was straightforward with: titles = driver.find_elements_by_class_name("sln_lot_show") for title in titles ...

The HTTP.GET method seems to be malfunctioning

I'm having some trouble loading an image from a HTTP.GET request into my application. The picture just won't seem to display correctly. Any suggestions on what might be causing this issue? Below is the code I am using: HTML: <ion-view view- ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Utilize a unique CSS selector and content property to insert a space character between two inline-block elements

I have a group of connected span elements with the class tag from bootstrap v4. Because they are generated from a react.js array of JSX elements, they sit adjacent to each other without any spacing between them: <span class="tag tag-primary">text< ...

obtain a Javascript variable within a Jade template by using inline code

script. var hide_section = 'block'; .title(style='display:#{hide_section}') I received an undefined value, any thoughts on why? Could it be because #{hide_section} is trying to access a variable from the back-end, such as the cont ...

Obtaining an array through an AJAX request in JavaScript

I'm struggling with my ajax call setup: request = new XMLHttpRequest(); request.open("GET","/showChamps?textInput=" + searchChamp.value,true); request.send(null); request.onreadystatechange = function () { if (request.status == 200 && reques ...

Incorporating a full-page background into a specific view using AngularJS

In order to implement a fullscreen CSS background for a specific view in my app, I attempted adding a class to the body. However, this approach caused the background to persist in the cache and remain visible when switching views. The challenge arises fro ...

The Google Maps feature encountered an error (ReferenceError: google is not defined)

Utilizing the Google Maps API on my website to display multiple locations has been successful so far. However, an issue arises when attempting to determine the distance between two sets of latitude and longitude coordinates - resulting in an error message ...

It seems that there is a null value being returned in the midst of the

I have developed a model using express. While setting this in one function, it returns null in another function, forcing me to use return. What is the proper method to handle this situation? const Seat = function(seat) { this.seat = seat.seat; this. ...

What is the best way to implement a day timer feature using JavaScript?

I am looking for a timer that can automatically change the rows in an HTML table every day. For example, if it is Day 11, 12, or 25 and the month is February at 8 AM, the rows should display "Hello!". function time() { var xdate = new Date(); var ...

glyph containing an undesirable space filled in

I have a character that I want to draw. The outline is correct but the filling isn't showing up as expected. Take a look at the comparison below (1. is what I want, 2. is what I currently have): c.beginPath(); //draw the curves c.closePath(); c.fi ...