Search code examples
ruby-on-railsrubyajaxformsrjs

rails form_remote_tag and onselect submit


I have a form_remote working perfectly for the form currency. The only change I want to make is the do away with submit button for a select box. So they just click the correct currency and it submits the ajax request.

<%= collection_select(:currency, :set, Currency.find(:all, :conditions => 'primary_source = "ECB"'), :code, :pretty_name, { :selected => session[:currency] }, { :onchange => "$('currency').submit()" } )  %>

The onchange works for the select, but instead of using the remote ajax request, it refeshes the entire page... instead of just one element, how can I initiate the remote_tag so that it does the same thing clicking submit would?


Solution

  • The problem you're having is that Rails implements remote_form_for as an inline Ajax method in the onsubmit attribute of the form. The problem is that the submit event only fires when a user physically submits the form, not by calling $('form').submit(). Actually I believe some browsers may fire the event but others don't. In any case, this won't work in the general case as you discovered.

    One possible workaround, and I have only tested this in Firefox 3.5, so your mileage may vary, is to call the attribute as a function directly. So inside your :onchange put:

    $('currency').onsubmit()
    

    If that doesn't work you may need to look at the generated source, and pull the AJAX request out of the onsubmit attribute and into a standalone method that you can call directly.

    As far as I know there is no cross-browser way to reliably fire a native event.