How to make dynamic dropdown in Rails?

瘦欲@ 提交于 2019-12-10 10:46:54

问题


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!?


回答1:


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 %>


来源:https://stackoverflow.com/questions/5590561/how-to-make-dynamic-dropdown-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!