Looking to display the precise information from an opened Accordion in a modal window for updating purposes with Django

My main goal is to update data using a modal toggle button within a bootstrap accordion. Each question is retrieved from views.py and displayed within an accordion element. The ideal scenario is for each accordion to have a modal toggle button that, when clicked, opens a modal containing the specific question from that accordion for updating.

The issue I am facing is that in the current implementation, clicking the modal button of the first question correctly displays the data for that question. However, when clicking the modal button of the second accordion (which contains a different question), it still shows the data for the first question. I'm struggling to find a solution to have each modal display the respective data for the corresponding accordion. Below is a snippet of my template file:

{% extends 'base.html' %}
{% block title %}Add Questions{% endblock title %}

{% block body %}
    <body>
    <label for=""><h4 style="color: indianred">Grade >> {{classname}} >> {{topicname}} >> {{subtopicnames}}</h4></label><br>
       <br>
    <br>
    <br>
    
    </div>
    </form>

    <div class="panel-group" id="accordion">
        {% for x in queryset %} <!-- retrieving all questions from views.py-->
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}">
                        Question
                    </a>
                </h3>
            </div>
            <div id="collapse{{ forloop.counter }}" class="panel-collapse collapse">
                <div class="panel-body">
                    
                    <!-- <input type="button" onclick="updateques();" value="Edit!!"><br>                      -->
                    <br><br>
                    <div>
                            {{x.question.id}}
                            <input type="hidden" id="quesid"  name="quesid" value="{{x.question.id}}">
                            <label>Q- <input type="text" id="ques" name="ques" value="{{x.question.question}}" readonly></label><br><br>
                            <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br>
                            <label>A- <input type="text" id="op1" name="" value="{{x.option.option1}}" readonly><br><br>
                            <label>B- <input type="text" id="op2" name="" value="{{x.option.option2}}" readonly><br><br>
                            <label>C- <input type="text" id="op3" name="" value="{{x.option.option3}}" readonly><br><br>
                            <label>D- <input type="text" id="op4" name="" value="{{x.option.option4}}" readonly><br><br>
                            
                            <input type="checkbox" name="" value="{{x.answer}}" checked>
                            <label>{{x.question.difficulty}}</label>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Edit</button>
                        
                    </div>
                    
                </div>
            </div>

            {{x.question.id}} <!-- checking here if it returns the right question id value of the accordian that is opened and it displays the correct id value but when it comes to modal it takes only the 1st question id and its data-->
            <!--Button trigger modal-->


            <!--Modal-->
            <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                    <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="quesid"  name="quesid" value="{{x.question.id}}">
                            <label>Q- <input type="text" id="ques" name="ques" value="{{x.question.question}}" readonly></label><br><br>
                            <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br>
                            <label>A- <input type="text" id="op1" name="" value="{{x.option.option1}}" readonly><br><br>
                            <label>B- <input type="text" id="op2" name="" value="{{x.option.option2}}" readonly><br><br>
                            <label>C- <input type="text" id="op3" name="" value="{{x.option.option3}}" readonly><br><br>
                            <label>D- <input type="text" id="op4" name="" value="{{x.option.option4}}" readonly><br><br>
                            
                            <input type="checkbox" name="" value="{{x.answer}}" checked>
                            <label>{{x.question.difficulty}}</label>
                    
                    </div>
                    <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Understood</button>
                    </div>
                </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

{% endblock body %}

When I tried moving the modal code inside the panel body, it only worked for the first accordion and not for the others. Placing the modal code inside the template for loop resulted in all accordions opening the modal but displaying data only for the first accordion. Any suggestions on how to achieve the desired outcome are greatly appreciated.

Answer №1

For a more efficient approach, consider moving the entire modal outside of the for-loop and utilizing only one modal for all questions. This way, when a user clicks the edit button, you can easily clone the entire contents div and add that cloned content inside the modal-body. Since you are displaying content inside the modal that is already present inside the accordion, you can simply extract the entire HTML from the accordion.

Check out the Demo Code below :

$("button[data-toggle='modal']").on("click", function() {
  var selector = $(this).closest(".contents").clone(); //clone whole div
  selector.find("button").remove() //remove modal button
  selector.find("input").prop("readonly", false); //remove readonly..from inputs
  //you can remove/add/manipulate this cloned content..
  $(".modal-body").html(selector) //add that inside modal-body

})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="panel-group" id="accordion">
  <!-- retrieving all questions from views.py-->
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse1">
            Question
            </a>
      </h3>
    </div>
    <div id="collapse1" class="panel-collapse collapse">
      <div class="panel-body">
        <br/><br/>
        <!--added class here -->
        <div class="contents">
          <!--remove ids use class-->
          1
          <input type="hidden" name="quesid" value="1">
          <label>Q- <input type="text" name="ques" value="abc" readonly></label><br><br>
          <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br>
          <label>A- <input type="text" name="" value="A1" readonly><br><br>
               <label>B- <input type="text" name="" value="B1" readonly><br><br>
               <label>C- <input type="text" name="" value="C1" readonly><br><br>
               <label>D- <input type="text" name="" value="D1" readonly><br><br>
               <input type="checkbox" name="" value="A" checked>
               <label>Ok </label>
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">Edit</button>
        </div>
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">
        <a data-toggle="collapse" data-parent="#accordion" href="#collapse2">
            Question 2
            </a>
      </h3>
    </div>
    <div id="collapse2" class="panel-collapse collapse">
      <div class="panel-body">
        <br/><br/>
        <div class="contents">
          2
          <input type="hidden" name="quesid" value="2">
          <label>Q- <input type="text" name="ques" value="abc" readonly></label><br><br>
          <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br>
          <label>A- <input type="text" name="" value="A2" readonly><br><br>
               <label>B- <input type="text" name="" value="B2" readonly><br><br>
               <label>C- <input type="text" name="" value="C2" readonly><br><br>
               <label>D- <input type="text" name="" value="D22" readonly><br><br>
               <input type="checkbox" name="" value="A" checked>
               <label>Not Good </label>
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#staticBackdrop">Edit</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!--move the entire modal outside of the loop-->

<div class="modal fade" id="staticBackdrop" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">

        <!--all content will be placed here-->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>
</div>

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

"Exploring the depths of sub directories in Node.js: A guide to printing

Once again, I find myself stuck with node.js and in need of your assistance. I am attempting to write a script for the command line interface that will search for all subdirectories under the current directory (process.cwd), and only print out those that ...

Chrome renders the javascript source file in a jumbled and unreadable format

I'm new to a project and I've noticed that the javascript files I edit in my IDE appear differently in Chrome. For instance, here is a code snippet from Intellij: https://i.sstatic.net/1ygfg.png Even though this code is in a file named MNV.js, ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Acquire the id_token from Google using oauth2

I am currently working with AngularJS on the client side and trying to implement Google OAuth2. While I have successfully obtained the access token, I now need to retrieve the ID token. In order to achieve this, I have made modifications in app.js, contro ...

Alexa Skills Issue: Problem with Playing AudioPlayer HLS Stream URL

I'm currently using the "AudioPlayer" feature from the "Alexa Skill Kit" to stream an HLS audio format URL. No errors are showing up from AWS Lambda or the Developer Portal. I've been testing it with Silent Echo (). Alexa can play MP3 URLs and so ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Avoid potential issues caused by cancelled asynchronous requests affecting the application's status by using the watchEffect() function

Imagine a scenario where a component receives the ID of a resource through a prop called resourceId. This component is responsible for fetching the corresponding resource from an API and displaying it, while also managing loading and error states (similar ...

Tips for waiting for a function to finish executing in node.js (using a for loop)

Currently, the issue lies in the fact that the for loop instantly loops through everything. However, I want it to pause before looping because each time the loop runs, it inserts data into the database (which takes time). Therefore, I would like it to wait ...

Add a square div in every direction around the existing content in an HTML file

Begin by locating square number 1. Once you press the + symbol above square 1, square 2 will appear. From there, you can click the + on the right side of square 2 to reveal square 3. Is it possible to achieve this sequence? If so, what is the best way to ...

What is the method for activating the open feature in react-dropzone-component by utilizing refs?

Currently, I am utilizing the react drop-zone component to facilitate file uploads to the server. My objective is to trigger the drop-zone open function upon clicking a button. Here is what I have experimented with so far: To reference the drop zone, I ...

Tips for centering a div horizontally when it exceeds the width of a mobile screen

My challenge is to create a circular div element that is wider than the mobile screen and perfectly centered. This circular div needs to be an exact circle, specifically targeted for mobile screens. I've attempted to achieve this using the code in th ...

Tips for minimizing padding in X-Range graphs

Is there a way to reduce the overall height of my X-Range chart by adjusting the padding on the Y axis around each series? I have experimented with different properties, such as adding groupPadding: 0, pointPadding: 0, and other parameters using this jsfi ...

Tips for incorporating JavaScript modules into non-module files

Learning how to use js modules as a beginner has been quite the challenge for me. I'm currently developing a basic web application that utilizes typescript and angular 2, both of which heavily rely on modules. The majority of my app's ts files ...

A guide on accessing a JSON file in Django with React using i18next

Running React build folder within Django leads to an issue where WSGI server uploads translation.json as text/html instead of json. Is there a method to specify this file as json or instruct WSGI server/Django to ignore treating it as json? In i18n.js, ca ...

Adding items from the JSON data to a nested array at index i

In my project, I am working with two files: index.js and list.json. My goal is to extract an element from list.json and insert it into a nested array following the structure [hour][visits per hour]. The hour refers to the index of the hour; for example, ...

Error: The AJAX request encountered an unexpected token in the JSON response

I am working with the following code snippet: $.ajax({ dataType: 'text', url: '/_/js/answers.json', type: "GET", success: function (data) { alert(data); ...

What causes my browser fingerprint to consistently remain unchanged?

declare var Fingerprint2: any; @Component({ selector: 'my-app', template: `Hello`, }) export class App { constructor() { new Fingerprint2().get(function(result, components){ console.log(result); // Device fingerprint as a hash va ...

Intermittent Cloudfront Content Delivery Network (CDN) disruptions (monitoring) - Implementing CDN Fail

Over the past two months, I've been dealing with sporadic issues involving Amazon Cloudfront. These failures occur 2-3 times a week, where the page will load from my web server but assets from the CDN linger in pending status for minutes at a time. It ...

Implementing Typescript for managing state in React components

Currently, I have a state set up like this: const [newInvoice, setInvoice] = useState<InvoiceType | null>(invoice) The structure of my InvoiceType is as follows: customer_email: string customer_name: string description: string due_date: stri ...

Toggle the on and off functionality of a button using ajax response for content display

I'm struggling to figure out why the button isn't working for me. I am familiar with how to enable and disable buttons using attr and prop. $(document).on("click", "#btn", function(){ $(this).html("Sending..."); $(this).prop("disabl ...