Open Multiple Bootstrap Modals

Asked

Viewed 10,207 times

13

As per bootstrap documentation: Modal

Multiple modes are not supported and require additional code.

I am trying to open various modals within others, these modals are called external files with data-remote and I’m having a problem, they stay inside each other, it seems redundant but it’s like their index is in the same as the previous modal.

Update of remote method documentation:

Original:

This option is deprecated Since v3.3.0 and has been Removed in v4. We recommend Instead using client-side templating or a data Binding framework, or Calling jQuery.load yourself.

If a remote URL is provided, content will be Loaded one time via jQuery’s load method and Injected into the . modal-content div. If you’re using the data-api, you may alternatively use the href attribute to specify the remote source. An example of this is Shown Below: <a data-toggle="modal" href="remote.html"data-target="#modal">Click me</a>

Translation:

This option is obsolete since v3.3.0 and will be removed in version 4. We recommend using the remote client-side templating or data Binding or calling jQuery load method.

If a remote URL is provided, the content will be loaded once through the jQuery load method and injected into the div . modal-content. If you are using data-api, you may prefer to use the href attribute to specify the remote source. An example of this is shown below: <a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>

Example:

Page 1:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title></title>
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
      <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet">
   </head>
   <body>
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

      <div class="modal fade" id="myModal" tabindex="-1" data-remote="pagina2.html" role="dialog" aria-labelledby="myModalLabel">
         <div class="modal-dialog" role="document">
            <div class="modal-content">
            </div>
         </div>
      </div>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
      <script type="text/javascript">

      </script>
   </body>
</html>

Page 2:

<div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
   <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal 2</button>

</div>
<div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   <button type="button" class="btn btn-primary">Save changes</button>
</div>



<div class="modal fade" id="myModal2" tabindex="-2" data-remote="pagina3.html" role="dialog" aria-labelledby="myModalLabel">
   <div class="modal-dialog" role="document">
      <div class="modal-content">
      </div>
   </div>
</div>

The result will be something like: inserir a descrição da imagem aqui

How could I solve this problem ?

  • 1

    Has a very good plugin called Bootbox to create Alerts, confirms and prompts, in all my projects I do not fail to use them for practicality. It implements the multi-modal maybe take a look at his code will help.

  • 1

    Why create multiple modals if you can concentrate everything on a single modal? Simply change the content, text, form, etc. when loading it.

  • These modals are used in various parts of the system, this way I use data-remote to call each of the screens, they can be modal or not, use everything in a requires code rewriting in various parts of the project thing I want to avoid as much as possible

  • You just need to tell what the layout of the modal will be loaded. You don’t need to create 500 modals for this.

  • You have an example ?

  • the modals are all the same, you have the buttons below, a heading in the header and the content in the middle.

  • when you load the boostrap modal, you pass the parameters via ajax by jquery, in the data-xxxx-ball attribute, or data-yyyy-square, these parameters can be captured and restructure your modal.

  • here are some examples: http://opensource.locaweb.com.br/locawebstyle/documentacao/componentes/modal/

  • As an example: http://jsfiddle.net/filadown/Lyp615jw/ in the 3 open modal I use data-remote to load a page, and on this page it has another modal that should open, but when it opens instead of staying in the normal Indice it becomes an Indice of the open page.

  • because you do not use the same function jquery dialog() with modal parameter=true https://jqueryui.com/dialog/#modal-form

  • @Sneepsninja All right ? Please read the description of the reward she answers your question rsrs.

  • ah sorry had not seen.. rsrsr

  • @Sneepsninja Pois eh no jqueryui I am ninja in creating modals and it works cool, but I switched to bootstrap and the only resource I could not pass to Bootsrap was it, the worst and that if you go in jqueryui.com and download only with basic(Dialog) will be js/css = 100KB

  • 1

    @Highlander updated the response, stayed in section 2 of the post, running using remote and href.

  • @petersonfortes As soon as possible I will be conducting the new tests, thank you!

Show 10 more comments

6 answers

6

  • I used your model to create a modal within the while. But when opening a modal, I saw by F12 that it creates an element { padding-right:17px} and with each modal I open it adds up to 17px; ... I have analyzed my files and found no padding. Do you know what is creating this element?

  • this problem that is occurring is probably because of the button reference.

  • Fala cara.... was your tutorial that I followed... in case you talk about which button? It was that block of Modal is not used... what is bringing the data this line: <a href="single.php? id=<? php echo $posts['id']? >" data-id="1" data-toggle="modal" data-content="<H2>Example title 1</H2><p>Content within modal 1</p>" data-title="This title is attribute 1" data-target="#element" data-button="change text of save button" title="? php echo $posts['title']; ?>" >

  • I am treating this problem by this link: http://answall.com/questions/83128/multiplo-modal-bootstrap-js-php?lq=1

  • Ivan I removed the buttons, but the problem persists.

  • @Ivanferrer You could re-edit your answer to fit the question better, I had to re-edit my question to include important information and put a functional example of the problem.

  • @Ivanferrer in this way all modals would be on one page only, as it would be if you call the modal 1 of another page and in the modal 1 Voce call the modal 2 that is on another page ?

  • Bootstrap modals also open to an external page link:<a href="sua-url.html" data-toggle="modal" data-target="#myModal">abrir modal</a> being on the same page. Just pass the URL. Just embed the content that will be displayed inside the div. No html markup required, only the content.

  • You can also implement within Bs.modal: var url = $(this).find('[data-url]').data('url');&#xA; if (url != undefined && url != '') {&#xA; var id = $(this).attr('id');&#xA; $('#'+id+' .modal-body').load(url);&#xA; } and pass url as attribute data-url="sua-url.html"

  • I updated the example url, "just one more little trend" by loading an external url.

Show 5 more comments

3

You can try dealing with multiple modals by working with the backdrop and the Z-index modal.

Like?

Using setTimeout, for the .modal-backdrop is not created when the event show.bs.modal is triggered.

I believe that this code should help.

Reference


Now, how about using the data-remote, once a Modal object is instantiated, it is connected to the target element. Each subsequent call will not update the values in the options of the remote. So that attributes are different for each instance, when Modal is switched, the value of data-remote is not being updated.

In addition to the previous fact, the plugin responsible for Modal loads the data-remote in the constructor of the Modal object, so that even if a change is made to the options of the remote it will never be recharged.

A possible gambit to be implemented would be:

$('body').on('hidden.bs.modal', '.modal', function () {
  $(this).removeData('bs.modal');
});

Or you can try to make things difficult and do something like check the page path that should appear in the modal, whether or not it is different from the previous one. If it is, destroy; if it is not, then there is no need to recharge.

$('[data-load-remote]').on('click',function(e) {
    e.preventDefault();
    var $this = $(this);
    var remote = $this.data('load-remote');
    if(remote) {
        $($this.data('remote-target')).load(remote);
    }
});
<a href="#myModal" role="button" class="btn" data-toggle="modal" data-load-remote="http://fiddle.jshell.net/q89Lhmss/0/show/" data-remote-target="#myModal .modal-body">Página 1</a>
<a href="#myModal" role="button" class="btn" data-toggle="modal" data-load-remote="http://fiddle.jshell.net/ng75mLnz/0/show/" data-remote-target="#myModal .modal-body">Página 2</a>
<a href="#myModal" role="button" class="btn" data-toggle="modal" data-load-remote="http://fiddle.jshell.net/jvr0dj61/0/show/" data-remote-target="#myModal .modal-body">Página 3</a>
<a href="#myModal" role="button" class="btn" data-toggle="modal" data-load-remote="http://fiddle.jshell.net/zsjq4u8z/0/show/" data-remote-target="#myModal .modal-body">Página 4</a>

<div class="modal hide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal Principal</h3>
  </div>
  <div class="modal-body">
    <p>Alguma coisa</p>
  </div>
  <div class="modal-footer">
    <button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Fechar</button>
  </div>
</div>

Working example HERE.

Reference

  • 1

    This is exactly what I want to avoid, I am using jQueryUI dialog to do this and I will leave it to use another that does the same ? Interesting would be to extend the modal function to support these two functions.

  • @Highlander updated the answer, to try to help in this context too, any questions just ask.

  • +1 Testing your solution

  • @Highlander worked as expected?

  • It didn’t work, this example does the same thing as my example: http://jsfiddle.net/filadown/Lyp615jw/ did you get my code in the question and simulate the problem ? creates Pag1 puts the content creates the pag2 puts the content, creates the pag 3 and tries to open them in the modal.

  • When you declare them on the same page all right the problem is when they are on another page and are called by the data-remote that works as a load

  • @Highlander please check if the current answer helps you in the data-remote problem, if I haven’t understood the problem a fiddle with the error found example might help .

Show 2 more comments

2

In Bootstrap remote modals are opened in modal-content and remote content, or modal remote, has the basic parts as header, body and footer. You should repeat by logic. The question is como é que você vai renderizar o segundo, terceiro, quarto... modais se no primeiro dado remoto o modal não carrega uma classe 'modal-content'?

Explain!

You have it on the front page:

<a class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</a>

<div class="modal fade" id="myModal" tabindex="-1" data-remote="http://fiddle.jshell.net/hwksuycy/20/show/" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    
    
    <!-- é essa classe que importa no Bootstrap 3.5 -->
    <div class="modal-content">
        <!-- o segundo modal será carregado aqui ou terá como alvo (target) esse elemento âncora, a CLASSE modal-content -->  
    </div>
  </div>
</div>

See the FIDDLE

The class modal-content is what really matters here, how can it be seen in the documentation.

Now, on the remote page you have the following:

<div class="modal-header">
   <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
   <h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
   <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal2">Open Modal 2</button>

</div>
<div class="modal-footer">
   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   <button type="button" class="btn btn-primary">Save changes</button>
</div>



<div class="modal fade" id="myModal2" tabindex="-2" data-remote="pagina3.html" role="dialog" aria-labelledby="myModalLabel">
   <div class="modal-dialog" role="document">
      <div class="modal-content">
      </div>
   </div>
</div>

That is, you have primarily the content structure of a modal, but you don’t have the class modal-content that was the anchor of the second modal, which carries a modal-content, but it doesn’t have a parent.

Well, a simple solution would be to use the extension Bootstrap Modal.

Take a look at the section "Stackable".

2

Follow example of doing this thing ai with jquery ui

var $modal = $('<div>');
        $modal.css('line-height','1').html('teste1')
            .dialog({width :400,height: 250,modal: true,closeOnEscape: false,title:'Aviso',
                buttons: { Ok:function(){ $(this).remove(); } }
            }); 

var $modal = $('<div>');
        $modal.css('line-height','1').html('teste2')
            .dialog({width :400,height: 250,modal: true,closeOnEscape: false,title:'Aviso',
                buttons: { Ok:function(){ $(this).remove(); } }
            }); 
var $modal = $('<div>');
        $modal.css('line-height','1').html('teste3')
            .dialog({width :400,height: 250,modal: true,closeOnEscape: false,title:'Aviso',
                buttons: { Ok:function(){ $(this).remove(); } }
            }); 
var $modal = $('<div>');
        $modal.css('line-height','1').html('teste4')
            .dialog({width :400,height: 250,modal: true,closeOnEscape: false,title:'Aviso',
                buttons: { Ok:function(){ $(this).remove(); } }
            }); 
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

1


From what I understand you wish to abandon the jQueryUI.

Following its operation the shipment is made by method open, and in this open is loaded the new url using the load.

As it is in jQueryUI:

HTML example:

 <!-- DECLARANDO DIV -->
 <div id="cliente">

Example JS:

$('#cliente').dialog({
   autoOpen: false,
   height: 550,
   width: 860,
   modal: true,
   title: 'Cliente',
   show: "blind",
   buttons: {
      'Sair': function () {
         $(this).dialog('close');
      }
   },
   position: {
      at: 'top'
   },
   open: function () {
      $(this).load('cliente.html'); // Aqui permitimos que seja carregado a página.
   }
});

// Chamando a dialog no click 
 $('#cliente').dialog("open");

Now playing this structure in Bootstrap:

HTML example:

 <!-- DECLARANDO DIV -->
 // Apenas acrescentamos a classe para dar o efeito do Bootstrap.
 <div id="cliente" class="modal fade">

Example JS:

function loadModal(id,url){
    $('#' + id).on('show.bs.modal', function () {
        $(this).load(url);
    });
}
// Chamando a função:
loadModal('Cliente','cliente.html')

// Chamando a modal no click, você pode usar tanto js quanto html usando o href:
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Cliente</a>

And your pages should include all content within the class modal-dialog:

<div class="modal-dialog">
  <div class="modal-content modal-lg">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <h4 class="modal-title">Modal 1</h4>
    </div>
    <div class="container"></div>
    <div class="modal-body">
      <h1> Algum conteúdo aqui.</h1>
    </div>
    <div class="modal-footer">
      <a href="#" data-dismiss="modal" class="btn btn-danger">Pesquisar</a>
    </div>

    <div class="modal fade" id="myModal3" data-remote="index3.html">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">

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

Within these included pages you can open as many modals as you want using the função loadModal().

Just don’t forget to declare div on the home page.

I await your Feedback.

  • 1

    Its solution was the simplest to solve this problem,.

1

I was able to do this by creating containers for each modal, each with a different z-index, so one modal could overlap the other.

<div id="modalContainer"><!-- seu primeiro modal aqui --></div>
<div id="subModalContainer"><!-- seu segundo modal aqui --></div>

And in the CSS:

#modalContainer { z-index: 100; }
#subModalContaineer { z-index: 1000; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.