Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Override a form's action url with `formaction`

Recently, I found myself with a form that needed to be able to submit to multiple urls. You can definitely use some javascript to get around this but that seemed like overkill for my situation. That’s when I learned about the HTML formaction attribute.

You can use this attribute on a submit tag and it will override the action specified by the form. Here’s an example with a Ruby on Rails form, but you just as easily do something similar with plain HTML -

<% form_with url: false do |f| %>
  <% users.each do |user| %>
    <%= check_box_tag "user_ids[]", user.id, false %>
  <% end %>

  <%= f.submit "Assign to Users", formaction: "/users/assign" %>
  <%= f.submit "Print for Users", formaction: "/users/print" %>
<% end %>

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction