How to open a Bootstrap modal with a specific tab active

ConorJohn picture ConorJohn · Oct 12, 2015 · Viewed 17k times · Source

I am trying to have the tab within the bootstrap modal open depending on what link is being clicked. No matter what I've tried it will only open up on the first tab. The two links are the following:

<a href="#tab-mileage" data-toggle="modal" data-target="#buyers-report-modal" >Mileage</a>
<a href="#tab-wrong-vehicle" data-toggle="modal" data-target="#buyers-report-modal">Wrong vehicle?</a>

and the markup for the modal is here:

<div class="modal" id="buyers-report-modal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-offset-top">
    <div class="modal-content">
    <div class="modal-body">
    <div class="sd-tabs sd-tab-interaction">
      <div class="row">
        <ul class="nav nav-tabs col-md-3 custom-bullet">

          <li class="active"><a data-toggle="tab" href="#tab-wrong-vehicle"> Wrong Vehicle?</a></li>
          <li><a data-toggle="tab" href="#tab-mileage"> Mileage</a></li>

        </ul>
        <div class="tab-content col-md-9">
          <form id="tab-wrong-vehicle" class="tab-pane active" action="" method="post"> <!-- Wrong Vehicle? -->

            <h3 class="tab-title">Tab 1</h3>

          </form> <!-- Wrong Vehicle? -->



          <form id="tab-mileage" class="tab-pane"> <!-- Mileage -->

            <h2 class="tab-title-resp hidden-md hidden-lg"> Mileage</h2>
            <h3 class="tab-title">Tab 2</h3>

          </form> <!-- Mileage -->

        </div>
      </div>
    </div>
  </div>
</div>

I need the modal to open up on the link that is clicked, for example,if I were to click on the second link it would open up the second tab in the modal. Any help would be greatly appreciated, I haven't been able to find a solution to this anywhere.

I left the original ID's in the code incase I made a mistake in replacing them.

Answer

Ramiz Wachtler picture Ramiz Wachtler · Oct 12, 2015

I've added a class .modal-toggle to the <a> elements which toggle the modals. Further, I've added some additional function which triggers on click and get's the href of the clicked element, after that I'm using tab("show") on the <a> element inside the <li> which matches the href. (I've added a close button inside your modal, so it's easier to test the demo)

$('.modal-toggle').click(function(e){
    var tab = e.target.hash; 
    $('li > a[href="' + tab + '"]').tab("show");
});

Demo Fiddle