質問をいただきました。
質問お願いします。
2つのプルダウンメニューを連動させたいのですがいい方法はありませんか?
Ruby on Railsによるプルダウンメニューの連動の簡単なサンプルを作りました。
サンプルということで、わかりやすさを重視しています。
Viewの方でプルダウンメニューを操作するJavaScriptの関数を用意しておき、
ControllerからJavaScriptの関数を呼び出すようにしました。
このあたりの処理は、いろいろなやり方があると思います。
index.html.erb
<%= javascript_include_tag(:defaults) %>
<script>
//プルダウンメニューが選択されたときに呼び出される関数
function change_item() {
<%= remote_function(:url => {:action => 'call_ajax'},
:with => "'id=' + $('item1').value") %>
}
//プルダウンメニューの選択肢を削除する関数
function clear_item() {
$('item2').length = 0;
}
//ブルダウンメニューに選択肢を追加する関数
function update_menu(name, value) {
$('item2').options[$('item2').options.length] = new Option(name, value);
}
</script>
<% form_tag do %>
<%= select_tag('item1',
options_for_select([['x','1'],['y','2'],['z','3']]),
:onchange => 'change_item()') %>
<%= select_tag('item2',options_for_select([])) %>
<% end %>
index_controller.rb
class IndexController < ApplicationController
def index
end
def call_ajax
# 選択肢のデータを取得
item_list = {
'1' => [['x1', '1'], ['x2', '2'], ['x3', '3']],
'2' => [['y1', '4'], ['y2', '5'], ['y3', '6']],
'3' => [['z1', '7'], ['z2', '8'], ['z3', '9']]
}
items = item_list[params['id']]
# Javascriptの呼び出し
render :update do |page|
#選択肢を削除
page.call 'clear_item'
#選択肢を追加
items.each { |item| page.call 'update_menu', item[0], item[1] }
end
end
end