Skip to content

Instantly share code, notes, and snippets.

@drewjoh
Created January 27, 2012 13:55
Show Gist options
  • Save drewjoh/1688900 to your computer and use it in GitHub Desktop.
Save drewjoh/1688900 to your computer and use it in GitHub Desktop.
Dynamic (AJAX) loaded Bootstrap Modal (Bootstrap 2.1)
$(document).ready(function() {
// Support for AJAX loaded modal window.
// Focuses on first input textbox after it loads the window.
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
if (url.indexOf('#') == 0) {
$(url).modal('open');
} else {
$.get(url, function(data) {
$('<div class="modal hide fade">' + data + '</div>').modal();
}).success(function() { $('input:text:visible:first').focus(); });
}
});
});
<a href="/url/to/load/modal_window.htm" data-toggle="modal">link</a>
<div class="modal-header">
<a class="close" data-dismiss="modal">&times;</a>
<h3>Modal header 2</h3>
</div>
<div class="modal-body">
<p>One body...</p>
</div>
<div class="modal-footer">
<a class="btn btn-primary" onclick="$('.modal-body > form').submit();">Save Changes</a>
<a class="btn" data-dismiss="modal">Close</a>
</div>
@ashwinkumarDhi
Copy link

Please help me out the above mentined issue? is it true that due to sorting Document i modified & that $(document).ready() function is unable to listen those changes..what is the solution for this, please get out me this issue..

@Sethathi
Copy link

Thanks!!!!!!!!!!!!!

@archonic
Copy link

archonic commented Nov 5, 2013

Thanks @drewjoh! This saves me from having a totally absurd amount of static HTML for various modals.

I got rid of the success in event in favor of the autofocus attribiute. (http://www.w3.org/wiki/HTML5_form_additions#autofocus)

@Manawyrm
Copy link

Thanks!

@aemxn
Copy link

aemxn commented Aug 22, 2014

Thanks for a very straighforward script

@shebinleo
Copy link

Thanks, very useful.

@sayolie
Copy link

sayolie commented May 13, 2016

Thanks @drewjoh great job; please can someone help me on how to pass variable to a remote php file using Ajax $.get, thanks

@alexseif
Copy link

Good solution, but the problem here is that the function get's triggered twice, I changed it to
data-toggle="ajax-modal"

@navdeepsingh
Copy link

navdeepsingh commented Jul 4, 2016

To remove dynamic modal loaded in DOM. the following works for me.
$('<div id="clue-modal" class="modal fade" tabindex="-1" role="dialog"><div class="modal-dialog"><div class="modal-content">' + data + '</div></div></div>').modal().on("hidden.bs.modal", function () { $(this).remove(); });

Can check https://gist.github.com/navdeepsingh/de4718a074b812637330f668d2a73b7e

Thanks!!

@lonely173
Copy link

Gracias,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment