Opening Targeted Tabs in a Bootstrap Modal Window

JavaScript
Bootstrap
Frontend
Archive
Fix Bootstrap modal tabs not rendering non-active tab content — trigger tab show and modal reset via JavaScript when opening a modal to a specific tab.
Author

B. Talvinder

Published

March 24, 2014

From the Archive

Originally published in 2014 on talvinder.com. Some technical details may be outdated, but this remains here as part of the archive.

I was trying to build a modal window in Bootstrap with 2 tabs. Each tab will be fired by different buttons in the main HTML.

The problems:

  1. Bootstrap doesn’t render the non-visible tab
  2. The modal window retains its last seen state

So for example, let’s say you’re building a checkout page and want to give the user options of both discount and partial payment.

You give 2 buttons in HTML, one each for discount and for partial payment.

On clicking the buttons, a modal window opens with 2 tabs – discount and partial payment. If the user clicked on the discount button, they should see the discount tab. If they clicked on partial payment, the partial payment tab should show with its content rendered.

Bootstrap by default doesn’t support this. If the user clicks the discount button, the discount tab displays fine. But if they then click partial payment, the content won’t be rendered. Same repeats when the partial payment button is clicked first.

Used a bit of JS to make this work. The approach: on the button click event, programmatically call .tab('show') on the target tab before opening the modal, and reset the modal’s state so it doesn’t retain the previous tab. This forces Bootstrap to render the target tab’s content fresh each time.

The full solution is available as a Gist: github.com/talvinder/9743198

Enjoyed this?

Get frameworks, build logs, and field notes in your inbox.

No spam. Unsubscribe anytime.