Bootstrap $('#myModal').modal('show') is not working - javascript

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.

Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).

<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked

This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector

I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup

My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>

Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.

the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.

Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>

Try This without paramater
$('#myModal').modal();
it should be worked

are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>

use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery

jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.

Please also make sure that the modal div is nested inside your <body> element.

After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it

In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.

Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz

Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Bootstrap v5 modal show issue

I decided to go ahead and update my site to the latest version of Bootstrap, version 5.0 and am having difficulty getting modals to work. Reading the migration guide said nothing about breaking modals and my site worked perfectly before. My code uses javascript/jQuery to fire off the modal after the ajax loads the text. The ajax part still works fine, but it's not firing the modal after it retrieves it. I'm using the latest bootstrap.bundle.min.js.
$( document ).ready(function() {
$('.hourModal').click(function(){
var obj_id = $(this).data('id');
$.ajax({
url: 'ajax-multi.php',
type: 'POST',
data: {obj_id: obj_id,role:'some_role'},
//dataType: 'html',
success: function(response){
$('.modal-body').html(response);
//$('#hourModal').modal('show'); //Old way that worked great
var hourModal = new bootstrap.Modal(document.getElementById('hourModal'));
hourModal.show(); // New way I tried from the Bootstrap documentation
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<!-- Button -->
<button type="button" class="btn btn-secondary btn-sm py-0 me-1 hourModal" data-id="1">Blocks</button>
<!-- Modal -->
<div class="modal fade" id="hourModal" tabindex="-1">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Object Times</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The error I get is: Uncaught TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
Any help is greatly appreciated!
UPDATE:
As described below, I had to move bootstrap.min.js to the end of the page, after </body> and leave where I call jquery.min.js at the top in the header. Anyone have any idea why it has to be done this way?
Move your <script> with bootstrap at the end of the <body>. It fixed my Bootstrap 5 modal issue.
This issue is fixed in currently available 5.0.1
UPDATE:
Fixed in Bootstrap 5.0.1
I had the same problem. The only difference I use Webpack to build.
If you want to load your scripts from head section you can try to add async option.
This fixed the issue for me.
<script src="..." async="async"></script>
I had the same problem. I called jquery.js and bootstrap.js at the end of the html and before /body and it worked correctly.
mamantoha's suggestion seems to be the better way to handle this since it doesn't require moving the outside the section, and some people may have dependencies that require bootstrap to be loaded ahead of other scripts in the section.
In bootstrap 4 or 5 you maybe forgetting the '#' in
data-bs-target="#exampleModal"

How to change an href attribute through Javascript on a modal window

I've been searching and trying different ways to change an href attribute through Javascript. Few things have worked better than others.
The problem with this approach is that the variable on the href is not working. I guess there is a better way to include a variable within an html tag.
I'm really stuck on this so would appreciate any help.
Here is the code of the modal window:
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href=enlace target="_blank">OK</a>
</div>
</div>
And this the button that the user clicks on before the modal window is shown:
<script type="text/javascript">
var enlace;
</script>
<button onclick="enlace='https://cloqq.com/actividad/tu-aventura-interactiva';return false" id="" class="go-btn pink-bg">Empieza a crear
</button>
https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
You can use setAttribute to reassign the href, the way you're using javascript in html doesnt work like that.
const itemYouWantToUpdateHref = document.querySelector('.btn-ok')
function changeHref(link) {
itemYouWantToUpdateHref.setAttribute('href', link);
}
<a class="btn-ok" href="www.google.com" target="_blank">My link will change</a>
<button onclick="changeHref('www.youtube.com')">click to change href from google to youtube</button>
You can use your code itself with only some changes and without any script tag. look at code below:
<button onclick="window.enlace='https://cloqq.com/actividad/tu-aventura-interactiva'" class="go-btn pink-bg">Empieza a crear</button>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="modal-close">×</span>
<h1>¿Quieres seguir creando?</h1>
<a class="btn-ok" href="javascript:window.open(window.enlace||'defaultAddress', '_blank');">OK</a>
<!--
!! If you like to show an alert when the button is not clicked yet, try line below instead above line:
<a class="btn-ok" href="javascript:window.enlace?window.open(window.enlace, '_blank'):alert('Please click the Button first!');">OK</a>
-->
</div>
</div>
If you run above snippet and look at console, you can see all things is fine (but because Security problems this will not work with these URLs in current page and you should copy it in your project or an empty html file for seeing the result.)

time-picker in bootstrap modal dialog

I am trying to implement a time-picker in a boostrap modal dialog. However when I open the dialog the time-picker still looks like a normal text field which makes me believe that this jquery code is not running:
$('#timepicker1').timepicker(); // shown below
However I am able to get the time-picker to display using very similar code on a normal webpage. The problem seems specific to displaying it in a modal dialog.
Here is a link to the time-picker that I am using:
http://jdewit.github.io/bootstrap-timepicker/
Here is my modal dialog:
<div class="modal fade" id="dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">close</button>
<h4 class="modal-title" id="myModalLabel">New Event</h4>
</div>
<div class="modal-body">
<div class="input-append bootstrap-timepicker">
<input id="timepicker1" type="text" class="input-small">
<span class="add-on"><i class="icon-time"></i></span>
</div>
</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>
</div>
</div>
Here is my script that is suppose to initialize the time-picker
$( document ).ready(function() {
//$('#table').editableTableWidget();
$( "#btn-new-event" ).click(function() {
$('#dialog').modal('show');
$('#timepicker1').timepicker(); // not running properly
});
});
Any help would be greatly appreciated!
For me, I had to do this to make it work:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 99999!important;
}
and of course, remove:
template: 'modal'
ibrahimyilmaz gave you the right answer, exactly as shown on the bootstrap timepicker official site.
The only thing that maybe serves as a more precise indication here is that timepicker only works with bootstrap v2.x.
If you want to use bootstrap 3.x, you have to read the migration doc and perform the required changes. If you need help on that, just give me a sign :) Or use timepicker bootstrap3 wich is a fork of the one you have used.
Check this link example to see a working example. Check on the +view Source link to see all the required scripts and links.
Hope it's useful!
$('#timepicker1').timepicker({
template: 'modal'
});
It's a reported bug https://github.com/jdewit/bootstrap-timepicker/issues/326
you have to change the z-order as mentioned by #eugene1832:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
AND you also need to remove the initialization option:
template: 'modal'
To update the answers to this question: bootstrap-timepicker now supports Bootstrap 3, but this issue with modals is a known bug.
The bug is still open at this time, but one user suggested adding this piece of code to your css file to make the timepicker visible:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
I would note that this solution did not work for me, but it is currently listed as a possible solution. I'll try to update this response when the issue is either resolved on Github or when someone suggests another method.
Add this code for line #666 in bootstrap-timepicker.js file. It's work for me
var index_highest = 0;
$(".modal").each(function() {
// always use a radix when using parseInt
var index_current = parseInt($(this).css("zIndex"), 10);
if (index_current > index_highest) {
index_highest = index_current;
}
});
var zIndex = parseInt(this.$element.parents().filter(function() { return $(this).css('z-index') !== 'auto'; }).first().css('z-index'), 10) + index_highest;

Modal error - Uncaught TypeError: undefined is not a function modal

Im using the following code and I got error in delete in the JS($("#deleteModal").modal("show");),any idea what can be wrong here ?
Im using MVC5 project
the error is
Uncaught TypeError: undefined is not a function
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="deleteModalLabel">Delete Item</h4>
</div>
<div id="deleteModalBody" class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(function () {
$("#deleteModal").modal("hide"); // initially hides the modal pop-up until needed
$(".deleteLink").on("click", function () {
$.get('#Url.Action("GetDeletePartial")', { id: $(this).prop("id") }, function (data) {
$("#deleteModalBody").html(data);
$("#deleteModal").modal("show"); // shows the modal pop-up now that we have our partial view
});
});
});
</script>
when I try it like following it fail in the begging of the script with the same error
#section scripts
{
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script>
$(function () {
$("#deleteModal").modal("hide"); // initially hides the modal pop-up until needed
$(".deleteLink").on("click", function () {
$.get('#Url.Action("GetDeletePartial")', { id: $(this).prop("id") }, function (data) {
$("#deleteModalBody").html(data);
$("#deleteModal").modal("show"); // shows the modal pop-up now that we have our partial view
});
});
});
</script>
}
It seems that you are attempting to make a model dialog using some third-party jQuery plugin, but you foget to make a reference to that plugin's javascript file.
To confirm this, i wonder which line does the exception occurs on? Is it on the line of first line of your ready callback?
$("#deleteModal").modal("hide");
If so, please check your script reference. Just add a <script> tag with a src to that file before your script block.
Update:
As you comments, the exception does not occurs on that line. So you may use a debugger(such as Chrome developer tools) to find out which function-call fails. You can set the debugger to pause the excution on exceptions.
In chrome developer tools, you can switch to Source tab and click the last icon on right-top of the side-bar on the right to enable this feature. Here's an awesome answer with snapshots: https://stackoverflow.com/a/17324511/1817042
Had the same error on standalone plain old HTML+Javascript page.
Apparently caused by socket.io.js which script tag was initially placed after jquery and bootstrap.js script tags.
Moving socket.io.js script tag before jquery and bootstrap resolved the issue for me.

How to hide Bootstrap modal with javascript?

I've read the posts here, the Bootstrap site, and Googled like mad - but can't find what I'm sure is an easy answer...
I have a Bootstrap modal that I open from a link_to helper like this:
<%= link_to "New Contact", new_contact_path, {remote: true, 'data-toggle' => 'modal', 'data-target' => "#myModal", class: "btn btn-primary"} %>
In my ContactsController.create action, I have code that creates Contact then passes off to create.js.erb. In create.js.erb, I have some error handling code (a mix of ruby and javascript). If everything goes well, I want to close the modal.
This is where I'm having trouble. I can't seem to dismiss the modal when all goes well.
I've tried $('#myModal').modal('hide'); and this has no effect. I've also tried $('#myModal').hide(); which causes the modal to dismiss but leaves the backdrop.
Any guidance on how to close the modal and/or dismiss the backdrop from within create.js.erb?
Edit
Here's the markup for myModal:
<div class="modal hide" id="myModal" >
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Add Contact</h3>
<div id="errors_notification">
</div>
</div>
<div class="modal-body">
<%= form_for :contact, url: contacts_path, remote: true do |f| %>
<%= f.text_field :first_name, placeholder: "first name" %>
<%= f.text_field :last_name, placeholder: "last name" %>
<br>
<%= f.submit "Save", name: 'save', class: "btn btn-primary" %>
<a class="close btn" data-dismiss="modal">Cancel</a>
<% end %>
</div>
<div class="modal-footer">
</div>
</div>
With the modal open in the browser window, use the browser's console to try
$('#myModal').modal('hide');
If it works (and the modal closes) then you know that your close Javascript is not being sent from the server to the browser correctly.
If it doesn't work then you need to investigate further on the client what is happening. Eg make sure that there aren't two elements with the same id. Eg does it work the first time after page load but not the second time?
Browser's console: firebug for firefox, the debugging console for Chrome or Safari, etc.
to close bootstrap modal you can pass 'hide' as option to modal method as follow
$('#modal').modal('hide');
Please take a look at working fiddle here
bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use hidden.bs.modal event you can read more about modal methods and events here in Documentation
If non of the above method work, give a id to your close button and trigger click on close button.
The Best form to hide and show a modal with bootstrap it's
// SHOW
$('#ModalForm').modal('show');
// HIDE
$('#ModalForm').modal('hide');
I use Bootstrap 3.4
For me this does not work
$('#myModal').modal('hide')
In desperation,I did this:
$('#myModal').hide();
$('.modal-backdrop').hide();
Maybe it's not elegant, but it works
I was experiencing with that same error and this line of code really helps me.
$("[data-dismiss=modal]").trigger({ type: "click" });
I found the correct solution you can use this code
$('.close').click();
$('#modal').modal('hide');
//hide the modal
$('body').removeClass('modal-open');
//modal-open class is added on body so it has to be removed
$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class
I ran into what I believe was a similar issue. The $('#myModal').modal('hide'); is likely running through that function and hits the line
if (!this.isShown || e.isDefaultPrevented()) return
The issue is that the value isShown may be undefined even if the modal is displayed and the value should be true. I've modified the bootstrap code slightly to the following
if (!(typeof this.isShown == 'undefined') && (!this.isShown || e.isDefaultPrevented())) return
This seemed to resolve the issue for the most part. If the backdrop still remains you could always add a call to manually remove it after the hide call $('.modal-backdrop').remove();. Not ideal at all but does work.
(Referring to Bootstrap 3), To hide the modal use: $('#modal').modal('hide'). But the reason the backdrop hung around (for me) was because I was destroying the DOM for the modal before 'hide' finished.
To resolve this, I chained the hidden event with the DOM removal. In my case: this.render()
var $modal = $('#modal');
//when hidden
$modal.on('hidden.bs.modal', function(e) {
return this.render(); //DOM destroyer
});
$modal.modal('hide'); //start hiding
I had better luck making the call after the "shown" callback occurred:
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
This ensured the modal was done loading before the hide() call was made.
What we found was that there was just a slight delay between the call to our server code and the return to the success call back. If we wrapped the call to the server in the $("#myModal").on('hidden.bs.modal', function (e) handler and then called the $("#myModal").modal("hide"); method, the browser would hide the modal and then invoke the server side code.
Again, not elegant but functional.
function myFunc(){
$("#myModal").on('hidden.bs.modal', function (e) {
// Invoke your server side code here.
});
$("#myModal").modal("hide");
};
As you can see, when myFunc is invoked, it will hide the modal and then invoke the server side code.
Hiding modal backdrop works but then any subsequent opening of the modal and the backdrop doesn't hide like it should. I found this works consistently:
// SHOW
$('#myModal').modal('show')
$('.modal-backdrop').show();
// HIDE
$('#myModal').modal('hide');
$('.modal-backdrop').hide();
I used this simple code:
$("#MyModal .close").click();
I was experiencing the same problem, and after a bit of experimentation I found a solution. In my click handler, I needed to stop the event from bubbling up, like so:
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Here is the doc:
http://getbootstrap.com/javascript/#modals-methods
Here is the method:
$('#myModal').modal('hide')
If you need to open several times the modal with different content, I suggest to add (in you main js):
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
So you will clean the content for the next opening and avoid a kind of caching
$('.modal-backdrop').hide(); // for black background
$('body').removeClass('modal-open'); // For scroll run
$('#modal').modal('hide');
$('#modal').modal('hide'); and its variants did not work for me unless I had data-dismiss="modal" as an attribute on the Cancel button. Like you, my needs were to possibly close / possibly-not close based on some additional logic so clicking a link with data-dismiss="modal" outright would not do. I ended up having a hidden button with data-dismiss="modal" that I could programmatically invoke the click handler from, so
<a id="hidden-cancel" class="hide" data-dismiss="modal"></a>
<a class="close btn">Cancel</a>
and then inside the click handlers for cancel when you need to close the modal you can have
$('#hidden-cancel').click();
Even I have the same kind of issues. This helped me a lot
$("[data-dismiss=modal]").trigger({ type: "click" });
We need to take care of event bubbling. Need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
I realize this is an old question, but I found that none of these were really what I was looking for exactly. It seems to be caused by trying to close the modal before it's finished showing.
My solution was based on #schoonie23's answer but I had to change a few things.
First, I declared a global variable at the top of my script:
<script>
var closeModal = false;
...Other Code...
Then in my modal code:
$('#myModal').on('show.bs.modal', function (event) {
...Some Code...
if (someReasonToHideModal) {
closeModal = true;
return;
}
...Other Code...
Then this: (Note the name 'shown.bs.modal' indicating that the modal has shown completely as opposed to 'show' that triggers when the show event is called. (I originally tried just 'shown' but it did not work.)
$('#myModal').on('shown.bs.modal', function (event) {
if (closeEditModal) {
$('#myModal').modal('hide');
closeModal = false;
}
});
Hope this saves someone the extra research some day. I spent a bit looking for a solution before I came up with this.
In my case I was apparently trying to close the dialog too fast after showing it. So in my close modal function I used this:
setTimeout(() => {
$('#loadingModal').modal('hide');
}, 300);
document.getElementById('closeButton').click(); // add a data-dismiss="modal" attribute to an element in the modal and give it this id
I used this code -
Hide modal with smooth effect using Fade Out.
$('#myModal').fadeOut();
$('.modal-backdrop').fadeOut();
$('.modal-open').css({'overflow': 'visible'});
If you're using the close class in your modals, the following will work. Depending on your use case, I generally recommend filtering to only the visible modal if there are more than one modals with the close class.
$('.close:visible').click();
I was facing a similar problem where my custom modal would show via js but I could not hide it (there was no close button).
For me the solution was to add the content into a modal-dialog.
<div class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="loading">
<div class="modal-dialog">
loading
</div>
</div>
Without the modal-dialog it would happily show the modal, but it was impossible to hide it without the manual solutions in some of the answers here, some of which prevent you then being able to show the modal again.
This is the bad practice but you can use this technique to close modal by calling close button in javascript.
This will close modal after 3 seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
window.onload=function()
{
setInterval(function(){
$("#closemodal").click();
}, 3000);
}
</script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="closemodal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Some times
$('#myModal').modal('hide');
$('#myModal').hide();
does not get the job done so you need to add this to footer of your modal:
<button type="button" id="close_cred_modal" class="btn btn-secondary" data-dismiss="modal">Close</button>
and than add this line to close the modal
$('#close_cred_modal').click();

Categories

Resources