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>
$('#myModal').modal('hide');
is the correct syntax to close/hide the modal with idmyModal
(you can test this on the Bootstrap documentation page). Are you sure you have an element with this id on your page? Also, what are you trying to accomplish with this call? Your current implementation performs an Ajax request tonew_contact_path
and at the same time opens the modal with the contents of#myModal
– is this what you want? – OestriolmyModal
. I re-tried$('myModal').modal('hide')
and still no good. HM. In terms of what I'm trying to accomplish, I think it may have been incorrect to use the link_to helper. I've replaced this with:<a data-toggle="modal" href="#myModal" class="btn btn-primary">Add Contact</a>
since I don't really need a call tonew_contact_path
. I just want the modal to open and then deal with user input. Thanks for taking the time to respond. I'll see if I can't sort this out. – Allo$('#myModal').modal('hide');
(there is an#
missing in your comment). – Oestriol$('#myModal').modal('hide')
. J – Allo