Monday, June 12, 2006

Ruby on Rails : start_form_tag with onsubmit javascript event hook

[Continuing to follow my rule of "If I spend a few hours googling for it and can't find the answer, when I do find the answer, post about it."]

I wanted to add an onSubmit="getComment()" handler to a form that is managed by Rails:

<%= start_form_tag :action=>'update', :id=>@alert %>


I tried a whole variety of combinations of sticking my option on the end - calling it onsubmit, onSubmit, on_submit, wrapping it in option=>{..}, html_option=>{...}, wrapping the whole thing, and so on. In most cases all it did was take whatever I added and stick it onto the end of my action url so I'd have things like "/update/18onsubmitgetcomment".

Turns out you need to batch up all of the options that are meaningful to Rails together (using {...}), and then you can put in your own option which becomes an HTML option (i.e. just passed through to the page):

<%= start_form_tag({:action=>'update', :id=>@alert}, :onsubmit=>'getComment()') %>


Note that the action and id tags are within the curly braces, and my onsubmit tag is not.

I'm sure that this is the kind of thing where, now that I know it, I could easily spot something in the documentation that says exactly what I just said. But obviously something didn't click until I had an actual use for it, and only having tested things that fail, and found something that works, can I make the leap backward and say "Aha, now I get it."


Technorati Tags: ,

2 comments:

Blaine said...

Thanks for the post.

I am a ROR newb.

The challenge of the evening is to make a gallery interface that the user can changed the name, description, etc of the gallery, as well as arrange the artwork within a gallery.

Rails has the cool sortable_element('thumb_list', :url=> ... )
tag that sends Ajax calls when sorted. But i didn't want the list to save on sorting change. I wanted the user to click a button to save both the gallery specific data as well as the sorted listing.

So using your tip and a custom js func, I got it all to work...



function getComment(formObj) {
formObj.action += '?' + Sortable.serialize("thumb_list");
}

The Sortable.serialize turns the thumb_list into a query string and submits it as part of the action and the gallery specific fields get submitted as part of the post.

pretty slick.

Auston said...

Ok, how about this though:

If I want my event handler to trigger an ajax call that works with an action/method in my rails controller?