Rails App with Bootstrap Modal View containing for

2019-04-16 18:51发布

问题:

I have a rails app which presents a form for visitors in a modal view. When the submit button is clicked, I want the form to submit and the modal view to disappear without reloading the page behind it. I've tried binding the modal view's dismissal to the form's submit function in javascript, but it's not working correctly. I'm a javascript newbie, so I might not have scripted this correctly. Here's what I have:

<script type="text/javascript">
    $("document").on("submit", ".new_user", function() {
        $('.signup').modal("close");
    });
</script>
<fieldset>

      <!-- The sign up modal view -->
       <div id="signup" class="modal hide fade in" style="display: none;">  
        <% @user = User.new %>
        <%= form_for(@user, :remote => true) do |f| %>
        <div class="modal-header">  
          <a class="close" data-dismiss="modal">×</a>  
          <h3>Want to be notified when preorders start? Fill out this form!</h3>  
        </div>  
        <div class="modal-body">  
            <div class="field">
              <%= f.label :email %>
              <%= f.text_field :email, :class => 'modal_input'%>
            </div>
            <div class="field">
              <%= f.label :website %>
              <%= f.text_field :website, :class => 'modal_input'%>
            </div>
            <div class="field">
              <%= f.label :projects, "Projects you've worked on"  %>
              <%= f.text_area :projects, :size => "43x10", :class => 'modal_input' %>
            </div>
        </div>
        <div class="modal-footer">  
        <button type="submit" class="btn btn-success">Submit</button>
        </div>  
       </div>  
      <% end %>


       <!-- The modal view is triggered here -->
        <a data-toggle="modal" href="#signup" class="btn btn-primary
        btn-large btn-signup">Sign up</a>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
        <script src="/twitter-bootstrap/twitter-bootstrap-v2/js/bootstrap-modal.js"></script>
  </fieldset>

My javascript function isn't closing the modal view. What's wrong with the function?

EDIT: Updated the javascript function, still not working correctly

EDIT 2: Turns out javascript function isn't being called at all, if that's any help.

回答1:

close() is not a jQuery method and that is not how the Bootstrap modal library works. Also, the submit binding should be changed to be bound so that things inserted into the DOM after the binding has been setup.

You should probably change your function to something like this:

$(function () {
  $("document").on("submit", ".new_user", function() {
      $('.signup').modal("close");
  });
});

In addition, be sure that you have loaded in jQuery and the Bootstrap modal script files prior to this function.