now available

now available
Want fresh tech tips in your inbox?

Rails Select Tag and Onchange Event Calling a Remote Function with Default Option Selected


Here is a little code snippet that will fire off a request to update_client_path when you change the select field. This stands alone, rather than being apart of a larger form. The Client::CATEGORY argument is a hash, which I populated manually in my Client.rb model. It is something like this

CATEGORY = {:lead => "Prospective clients", :past => "Previous clients..."} 
In my view I have

<%= select_tag "client_category", 
 options_for_select(Client::CATEGORY.keys, @client.category.to_sym), 
 { :onchange => remote_function( :url => update_client_path(@client), :with=>"'change_to='+this.value+''" ) } %>
One gotcha is that the select_tag, options_for_select argument expects a symbol if you're passing in a hash as the type of the collection! It may not set the default if you provide it with a string for the second arg (which specifies which option should be set as selected).

You also need to make sure that the url update_client_path is set in your routes file and that your controller (clients_controller in this case) has the appropriate method to handle the request.

Tagged w/ #defaults #helpers #onchange #options_for_select #rails #select #select_tag #to_symruby on rails

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app