Bootstrap modal not closing on form submit - Rails

15,215

I've had a similar problem before, and the way I solved this was by adding a click event to the submit button:

$('#addSubmit').click ->
   $('#addListItem').modal('hide');

Hope this helps!

Share:
15,215
settheline
Author by

settheline

Updated on June 07, 2022

Comments

  • settheline
    settheline almost 2 years

    I have this modal in my view:

    <div class="modal fade" id="addListItem" tableindex="-1" role="dialog" aria-labelledby="addListItem" aria-hidden="true">
      ......
      ......
          <div class="modal-body">
             <%= form_for @list_item, :remote => true, :html => {:id => "addForm"} do |f| %>
                 <%= f.hidden_field :upc, :value => @item.upc %>
                 <%= f.hidden_field :inventory_item_id, :id => "inventoryID", :value => "" %>
                 <%= f.submit("Add It!", class: "btn", :id => "addSubmit") %>
             <% end %>
          </div>
      ......
      ......
    </div>
    

    Because the form is remote, I want this modal to hide on form submit. Here's how I do that:

    $('#addForm').submit(function() {
        $('#addListItem').modal('hide');
    });
    

    What's currently happening is puzzling me. When I hit submit, the form submits remotely and the modal stays open. When I hit the submit button a second time, the form submits again and the modal hides. Why is this modal not hiding on the first submit? Thanks in advance!