Pergunta

My page renders a form into html via jQuery. Occasionally, when I would click submit or press enter, the button turns to 'loading' state but the form doesn't submit, nothing happens on the server or the network tab, and the user has to reload the page to try to submit the form again. So I removed the button from the form and placed it just after as well as changed the jQuery to also submit the form when this button is clicked. This works fine but the user now cannot click enter to submit the form, an important use-case for my client. Does anyone know what might be the cause of the original issue or a potential fix? Thanks!

New jQuery

$("#add_order_btn").click(function(){
  $(this).button('loading');
  $("#new_order").submit(); # added as fix when button moved outside the form
});

New Form

<%= form_for(@new_order, url: add_order_url, method: "post", remote: true, class: "form-inline mb0") do |f| %>
      <%= f.text_field :order_start_date_time, class: "new-order-datetime input-medium", placeholder: "Start date & time", id:"new_order_time" %>
      <%= f.text_field :yrd, placeholder: "# of yards", class: "span2" %>
      <%= f.check_box :plus %>
      <%= f.label :plus, '<i class="fa fa-plus" id="go_plus"> </i>'.html_safe, class: "label_inline mr15" %>
      <%= f.text_area :notes, placeholder: "Private Dispatch notes", class: "span12", id: "new_text_area", rows: "1" %>
    <h4 class="mt5" id="new_order_extras">Order extras
      <%= link_to "Add", new_order_extras_url, remote: true %>
    </h4>
  <% end %>
  <%= button_tag '<i class="fa fa-list-alt"></i> New Order'.html_safe, class: "btn btn-primary btn-block btn-large mt5 mb15", id: "add_order_btn" %> # Moved out of form as fix
Foi útil?

Solução

I've had cross-browser trouble before with form submissions through a button click not generating the correct event. Also, if you have other handlers on the button they can sometimes interfere with the form-related events. When dealing with forms, I usually get better results using the submit event.

Put the button back into the form. Then catch the form.submit event instead of the button.click event.

$("#new_order").submit( function(evt) {
    evt.preventDefault();
    var btn = $(this).find('button[type=submit]');
    // Do whatever it is you do here to indicate the loading state
    //     handle the form submission
    // Undo your button load state
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top