There are two ways to dismiss a modal using jQuery:
modal()
andnbsp;method:JavaScript
$(and#39;#myModaland#39;).modal(and#39;hideand#39;);
andnbsp;
This will hide the modal with the ID myModal
. You can also use the class selector to hide all modals with a specific class:
JavaScript
$(and#39;.modaland#39;).modal(and#39;hideand#39;);
data-dismiss
andnbsp;attribute:This attribute can be added to any element inside the modal to dismiss it when the element is clicked. For example, you could add it to a button:
HTML
andlt;button type=andquot;buttonandquot; class=andquot;btn btn-defaultandquot; data-dismiss=andquot;modalandquot;andgt;Closeandlt;/buttonandgt;
When this button is clicked, the modal will be dismissed.
Example:
HTML
andlt;div class=andquot;modal fadeandquot; id=andquot;myModalandquot;
tabindex=andquot;-1andquot;
role=andquot;dialogandquot;
aria-labelledby=andquot;myModalLabelandquot;
aria-hidden=andquot;trueandquot;andgt;
andlt;div
class=andquot;modal-dialogandquot;andgt;
andlt;div
class=andquot;modal-contentandquot;andgt;
andlt;div
class=andquot;modal-headerandquot;andgt;
andlt;button
type=andquot;buttonandquot;
class=andquot;closeandquot;
data-dismiss=andquot;modalandquot;
aria-label=andquot;Closeandquot;andgt;andlt;span
aria-hidden=andquot;trueandquot;andgt;andamp;times;andlt;/spanandgt;andlt;/buttonandgt;
andlt;h4
class=andquot;modal-titleandquot;
id=andquot;myModalLabelandquot;andgt;Modal titleandlt;/h4andgt;
andlt;/divandgt;
andlt;div
class=andquot;modal-bodyandquot;andgt; ... andlt;/divandgt;
andlt;div
class=andquot;modal-footerandquot;andgt;
andlt;button
type=andquot;buttonandquot;
class=andquot;btn btn-defaultandquot;
data-dismiss=andquot;modalandquot;andgt;Closeandlt;/buttonandgt;
andlt;button
type=andquot;buttonandquot;
class=andquot;btn btn-primaryandquot;andgt;Save changesandlt;/buttonandgt;
andlt;/divandgt;
andlt;/divandgt;
andlt;/divandgt;
andlt;/divandgt;
JavaScript
// Dismiss the modal when the andquot;Closeandquot; button is clicked. $(and#39;#myModaland#39;).on(and#39;clickand#39;, and#39;[data-dismiss=andquot;modalandquot;]and#39;, function() { $(and#39;#myModaland#39;).modal(and#39;hideand#39;); }); // Dismiss the modal when the ESC key is pressed. $(document).on(and#39;keydownand#39;, function(e) { if (e.keyCode === 27) { $(and#39;#myModaland#39;).modal(and#39;hideand#39;); } });
You can also use jQuery to dismiss a modal programmatically, such as when a certain event occurs. For example, you could dismiss a modal when an Ajax request has completed successfully:
JavaScript
$.ajax({ url: and#39;/submit-formand#39;, type: and#39;POSTand#39;, data: $(and#39;#formand#39;).serialize(), success: function() { $(and#39;#myModaland#39;).modal(and#39;hideand#39;); } });