Follow Along as I Stumble on the Path to Learning RoR

Posts tagged “ajax

Triggering jQuery on Page Load

I had some jQuery on a page that changes with a change to a field in a form, like so:

<%= tax.select(:state , Order::STATES ,{:prompt => ‘Select State’}, :id => “state”,:onchange => “render_sales_tax()”) %>

The issue was that when a user received an error with the form and the user populated the field again (ie :state), then when the view was rendered again (ie format.html { render :action=>”new” }  ), the  jQuery would not be triggered again because the field was already populated when rendered again (so no onChange event).

To fix this, I had to add this line above the jQuery function in the <script> section of the page:

window.onload = render_sales_tax();

This way the jQuery triggered and then onChange it would update again (if necessary).


Links for using :remote for Ajax and Javascript in Rails 3

Some good articles on how to use Ajax/Javascript with Rails 3:

http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

http://rails.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#M002239

http://railscasts.com/episodes/294-playing-with-pjax