Search code examples
djangoaccordion

How to open specific Accordion item in Django using Bootstrap?


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


Solution

  • 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