bristophocles
bristophocles

Reputation: 143

Rails remote form submits when non-submit button clicked

I am creating a remote/ajax form in rails 4. Here is the code:

        <div id="new-email-form-section" class="new-attribute-section">
            <%= form_for [@user, @contact, @contact_email], :format => :js, :remote => true do |f| %>
              <input type="hidden" value="<%= form_authenticity_token %>" name="authenticity_token" />
              <div class="new-attribute-fields">
                <div id="new-email-form-tag">Label: <%= f.text_field :tag %></div>
                <div id="new-email-form-email">Email: <%= f.text_field :email %></div>
              </div>
              <div class="new-attribute-btns">
                <div id="new-email-submit">
                  <%= f.submit "Add", :class => "btn new-attribute-submit-btn" %>
                </div>
                <div id="new-email-cancel">
                  <button id="new-email-cancel-btn" class="btn new-attribute-cancel-btn">Cancel</button>
                </div>
              </div>
            <% end %>
          </div>

This form is hidden and displayed when user clicks a "show" link at the top of the page. Upon clicking the "Cancel" button, the form is again hidden with jQuery/Coffeescript, like so...

$(".new-attribute-cancel-btn").click ->
  $(this).closest(".new-attribute-section").hide()

When I click the "Cancel" button, the form is hidden... but the form is also submitted (via ajax). I assume rails is applying submit script to both my submit button as well as my "Cancel" button as it is enclosed within the form tags. Is there any way to avoid this? Or is placing this "Cancel" button within the form itself simply bad form (no pun intended)?

Upvotes: 0

Views: 1370

Answers (2)

KappaNossi
KappaNossi

Reputation: 2716

The problem is that a <button> also submits a form. Use <input type="button"> instead to show a "normal" button, which doesn't submit.

http://www.w3schools.com/tags/tag_button.asp

If you want to create the button using rails, use this helper:

<%= submit_tag l(:button_cancel), :name => 'form_cancel', :onclick => "hideForm(this);", :type => 'button' %>

Upvotes: 1

vee
vee

Reputation: 38645

You can prevent the default submission using event.preventDefault() on click event of the cancel button as:

$(".new-attribute-cancel-btn").click (evt) ->
  evt.preventDefault()
  $(this).closest(".new-attribute-section").hide()

Upvotes: 3

Related Questions