How to open specific Accordion item in Django using Bootstrap?

35 Views Asked by At

I have a Django app with a page that contains a Bootstrap Accordion.

I have a form in the third accordion item. On submit within that form I want the page to refresh to the same accordion item - I have some feedback messaging there that want to display to the user.

Currently on Submit the page refreshes to the default item - in my case that's the first accordion item.

I have tried appending /#collapseThree to the url, but the page refreshes to the default view.

Thanks, Andrew

2

There are 2 best solutions below

0
A. Jabbitt On BEST ANSWER

For anyone crossing this path in future here is my solution:

Original Problem: I have a Django template that contains a Bootstrap Accordion, with three items. In each item I have a form. When the page is refreshed on any submit it always opened to the first Accordion item. I wanted the page to open to the accordion item that raised the 'submit' event (this is because I do some server-side form validation and want to present messages to my user when they make a bad selection).

Solution: I was able to achieve this by adding a parameter to my template url in urls.py ('/str:active_accordion/'). I then made sure to call a form action on each of my three forms:

'action="{% url 'app:view' 'collapse???' %}"' 

... where: 'collapse???' in each case matches the id of the accordion item that contains the relevant form. Example 'collapseThree'

Finally I added the following script to my template to read the url and 'show' the appropriate Accordion item:

<script>
        $(document).ready(function() {
            // Check if the URL contains the open_accordion parameter
            var urlParams = new URLSearchParams(window.location.search);
            if (window.location.href.indexOf("collapseOne") > -1) {$('#collapseOne').collapse('show');}
            if (window.location.href.indexOf("collapseTwo") > -1) {$('#collapseTwo').collapse('show');}
            if (window.location.href.indexOf("collapseThree") > -1) {$('#collapseThree').collapse('show');}
        });
    </script>

Hope it helps someone else. Andrew

0
Pycm On

Use below procedure.

  1. Give your elements unique ids.

Like

<div id="tab1"></div>
<div id="tab2"></div>
<div id="tab3"></div>
<div id="tab4"></div>
  1. Give your urls tab id, that you need to focus
url_path#tab2
  1. Use js to focus tab with id from url
document.getElementById(window.location.hash).click();

//or

document.getElementById(window.location.hash).focus();