Obama '08
New-formula-starburst

jQuery and Rails trick - Multiple submit buttons for a single form

1

Say you have a HTML form with two buttons that you each want to submit to different RESTful actions. For example, an email form with a ‘Send’ and ‘Delete’ button, which should each POST to different actions.

With some intelligent conventions, and a few lines of jQuery, we can accomplish that nicely. Here’s a simplified example.

the RHTML View

<% form_for @message, :url => '', :html => { :id => 'message' } do |f| -%>
<%= f.text_field 'subject' %>
<%= f.text_field 'body' %>
<% end -%>
<button type="button" name="send">Send</button>
<button type="button" name="save">Save as Draft</button>

jQuery

  $(document).ready(function(){
    $("button").click(function() {
      $("form#message").attr('action', '/message/' + $(this).attr('name'));
      $("form#message").submit();
    });
  });

This will enable all the buttons on the page so that when clicked, the button will submit to /message/name where name is the name attribute on the button tag.

Comments

  • Avatar john said 18 days later:

    Thank you thank you ! :-)

    Nothing to do with rails but was trying something with php ie many products come from the db and can be edited (each in its own hidden div) and it was driving mental how to get with form / div the button was in !

    This is perfect

Trackbacks

Use the following link to trackback from your own site:
/articles/trackback/19497

(leave url/email »)

   Comment Markup Help Preview comment