Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Bootstap Modals and Cache

Hey everyone! I am building a Wordpress theme with bootstrap. I have a grid on the homepage with my companies projects on it. When you click on a project it opens in a bootstrap modal window coming in from the right. The problem is after closing the first option, the modal doesn't reset.

I've read somewhere that it could be to do with Ajax cache, and I have tried some options including, including this code in a script just above the footer:

$.ajaxSetup({ cache: false });

It doesn't seem to work for me. Can anyone offer me any advise. Thanks :)

1 Answer

Patrick Marshall
Patrick Marshall
13,508 Points

Hi David, I've actually experienced this on a project I was working on and found it to be quite annoying. The best solution I found is this:

          var originalModal = $( '#account_modal' ).clone();
            $( '#account_modal' ).on( 'hidden.bs.modal', function () {
                $( '#account_modal' ).remove();
                var myClone = originalModal.clone();
                $( 'main' ).after( myClone );
            } );

In short, clone the original modal before any values on the from have been changed. Then once you are done with the modal and it is hidden delete it and add the cloned original modal back to the body. The trick I found to this as well is that it needs to be in the same function that you use to show the modal. I tried it in $().ready function and it worked only one time. So it needs to be called every time you show the modal.

I found other methods such as resetting the form with $( 'form' )[0].reset(); when hiding the modal, which resets the data but not the values. Then you have to reset the values on the form as well. While this does work on some simple forms, I noticed that some values weren't released and when updating my database it updated the wrong record.

Hope this helps.