How to hide Bootstrap modal with javascript?

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?
Here’s the markup for myModal:

Related:  Initialize Firebase references in two separate files in the new API


Solution 1:

With the modal open in the browser window, use the browser’s console to try


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.

Solution 2:

to close bootstrap modal you can pass ‘hide’ as option to modal method as follow


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 event you can read more about modal methods and events here in Documentation

Related:  'this' in function inside prototype function [duplicate]

If non of the above method work, give a id to your close button and trigger click on close button.

Solution 3:

I use Bootstrap 3.4
For me this does not work


In desperation,I did this:


Maybe it’s not elegant, but it works

Solution 4:

I was experiencing with that same error and this line of code really helps me.

$("[data-dismiss=modal]").trigger({ type: "click" });

Solution 5:

The Best form to hide and show a modal with bootstrap it’s


Solution 6:

//hide the modal

//modal-open class is added on body so it has to be removed

//need to remove div with modal-backdrop class