Using Ruby on Rails’ View Helpers To Create a Javascript Form Reset Button

Posted on August 22, 2008

Apparently, it is possible reset an entire form using Javascript from a button using the Rails form helpers. Up until now, I’ve been sniffing the submit tag’s name in the controller and avoiding the save when posting an update. The beauty of the Javascript form reset method is that it requires absolutely no code in the controller.

Oddly enough, there did not exist any easily findable examples from Google. So, here is how to reset a form to the original using only Javascript.

<% form_for :person, person, :url => { :action => "update" } do |f| %>
# Other stuff
<%= f.submit "Cancel", :type => "button", :onclick => "this.form.reset()" %>
# Resets the form back to the original values set in the edit template
<% end %>
Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Wilmer Sat, 23 Aug 2008 03:52:40 UTC

    Seriously, who uses those reset buttons? Aren’t those just the bastards you sometimes accidentally push instead of Submit and then you end up rewriting everything you just already wrote? But somehow everyone makes them anyway since Tim Berners-Lee wanted it that way?

    Even your blag doesn’t have one! :-P

  2. Administrator Sat, 23 Aug 2008 12:34:06 UTC

    I’m in the process of adding a huge cancel button to the front page right now.

  3. kikito Tue, 01 Sep 2009 08:52:11 UTC

    Hey, you don’t need javascript for that.

    You can generate an html-only reset button by doing this:

    ‘reset’ %>

    But you’ll probably want to add a :name and :id parameters too:

    ‘reset’, :name => ‘reset’, :id => ‘reset’ %>

    Because by default these will be ‘object_submit’

    Regards,

    Kikito
    The :name and :idparameter is for t

  4. Soniya Ahuja Mon, 08 Feb 2010 18:40:01 UTC

    I tried the method specified by kikito, but it gave a submit button with reset text. What I did instead was this

    ‘reset’, :id => ‘reset’, :type => ‘reset’ %>

    This created an HTML reset button for me.

  5. Kido Tue, 24 May 2011 13:40:46 UTC

    Thanks for the solutions it’s work fine

Comments