Vishal
Vishal

Reputation: 717

How to open same modal with two different links with different behaviour?

I am having a modal that have two divs in it. Now i am willing to open the same modal with two different links.

Here is my modal:

  <!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <%= link_to "Back","#",class: "btn btn-default",id: "Back-Link",style: "display:none"%>
        <%= link_to "Next","#",class: "btn btn-default",id: "Next-Link"%>
        <div id="One">
          <p>Some text in the modal.</p>
        </div>
        <div id="Two" style="display:none">
          <p>Modal Two.</p>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

Following are the links:

<%= link_to "Test","#", 'data-toggle': "modal", 'data-target': "#myModal"%>
<%= link_to "Test1","#", 'data-toggle': "modal", 'data-target': "#myModal"%>

When I click on "Test" Link the modal should open with div id "One". And when i click on "Test1" the modal should open with div id "Two".

can anyone help me? Thank you in advance

Upvotes: 1

Views: 993

Answers (1)

Kumar
Kumar

Reputation: 3126

Here is a working fiddle.

I made use of the data attributes to store id of div to show inside the modal. Then on click of it, I changed its style from display:none to block.

<div class="modal-body">
  <div id="one" class="hide_first">
    <p>Some text in the modal.</p>
  </div>
  <div id="two" class="hide_first">
    <p>Modal Two.</p> 
  </div>
</div>



<a href="#" class="modal-open-links" data-toggle="modal" data-modal-show="one" data-target="#myModal">Open #One</a>
<a href="#"  class="modal-open-links" data-toggle="modal" data-modal-show="two" data-target="#myModal">Open #Two</a>
<!-- Storing the id of divs in data-modal-show -->

And write some javascript like this

//classes given to our links
$(".modal-open-links").on("click", function(e){

  //First set display:none for all divs
  $(".hide_first").css("display", "none");
  //hide_first class is on both our divs inside modal body that we want to alternatively show


  content_to_show = $(this).attr("data-modal-show");
  //the div id we want to show on modal open

  //Show the one we clicked
  $("#" + content_to_show).css("display", "block");
});

Upvotes: 1

Related Questions