hnprashanth
hnprashanth

Reputation: 831

How to make dynamic dropdown in Rails?

I'm working on a e-commerce project where there will be radio buttons for size selection. I have a dropdown for quantity. I want to make this dropdown dynamic based on stock available for the user selected size. Can anyone tell me how this can be done on Rails? without cluttering my view file with lot of javascript!?

Upvotes: 2

Views: 1015

Answers (1)

dhoelzgen
dhoelzgen

Reputation: 1150

If you are using Rails 3 with prototype (default afaik), you could use the prototype legacy helpers (Link on Github) to add an observer and render a partial view for your dropdown box. You could add an observer like this

<%= observe_field 'element_var_name',
      :url => { :action => "another_action_here" },
      :update => "div_tag_to_update",
      :with => "'selected='+ escape($('element_var_name').value)" %>

Be sure to adjust element_var_name and the action to your situation. div_tag_to_update is the div that will update with the dropdown box. The another_action_here action should render a view like this:

def call_ids_by_type
  @element_list = ... # whatever fits for you, like: [[key, value],[key, value]]
  render :layout => false
end

In the partial view, you can use the element list to generate the dropdown box:

<%= f.select :var_name, @element_list %>

Upvotes: 2

Related Questions