I have the following select list.
<%= select_tag "project_id", options_from_collection_for_select(@projects, "id", "title") %>
When the user selects an option from the above list, the list below should be populated with values from database based on the above selection.
<%= select_tag "version_id", options_from_collection_for_select(??project.versions??, "id", "title") %>
I think i should make use of the onchange event, but i have no idea on how to use it. Someone help me please. Thanks!
Javascript
function update_versions_div(project_id) {
jQuery.ajax({
url: "/update_versions",
type: "GET",
data: {"project_id" : project_id},
dataType: "html"
success: function(data) {
jQuery("#versionsDiv").html(data);
}
});
}
Controller
def edit
@projects = Project.all
@versions = Version.all
end
def update_versions
@versions = Version.where(project_id => params[:project_id]).all
render :partial => "versions", :object => @versions
end
View
<%= select_tag "project_id", options_from_collection_for_select(@projects, "id", "title"), :prompt => "Select a project", :onchange => "update_versions_div(this.value)" %>
<div id="versionsDiv">
<%= render :partial => 'versions', :object => @versions %>
</div>
Partial: _version.html.erb
<%= select_tag "version_id", options_from_collection_for_select(versions, "id", "title"), :prompt => "Select a version" %>
Also add a route for /update_versions
in your routes.rb
match "/update_versions" => "<controller>#update_versions"
Here, you should replace <controller>
with name of the controller.
I havent tested the code, so there may be errors.
Update
PullMonkey has updated the code with Rails 3 example, which is obviously superior than this code. Please checkout http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/ also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With