请教:三级联动下拉框的“联动”问题
目标是要实现一个选择省、市、县(区)的三级联动下拉菜单。
test.rhtml的代码:
<%= javascript_include_tag :defaults %>
<%= select(:city, :province_id, @provinces, options = {},
html_options = {"onchange" => remote_function(
:with => "'province_id='+value",
:update => 'city_select',
:url => { :action => :select_cities_with_ajax })})
%>
<div id='city_select'>
<%= select( :county, :city_id, @cities, options = {},
html_options = { "onchange" => remote_function(
:with => "'city_id='+value",
:update => 'county_select',
:url => { :action => :select_counties_with_ajax })})
%>
</div>
<div id='county_select'><%= select(:sth, :county_id, @counties) %></div>
_select_city.rhtml代码:
<%= select(:county, :city_id, @cities, {},
{"onchange" => remote_function(
:with => "'city_id='+value",
:update => 'county_select',
:url => { :action => :select_county_with_ajax } )} )
%>
_select_county.rhtml代码:
<%= select(:sth, :county_id, @sights) %>
controller代码:
def select_city_with_ajax
@cities = Province.find(params[:province_id]).cities.map{|u| [u.name,u.id]}
render :partial => "select_city"
end
def select_county_with_ajax
@counties = City.find(params[:city_id]).counties.map{|u| [u.name,u.id]}
render :partial => "select_county"
end
ok。这段代码是可以工作的,选择省份以后相应的城市列表会变,选择城市以后相应的区县列表也会变。但是,选择省份以后,一定要经过一个“选择城市”的过程,区县列表才会改变。如果你要选择的城市正好排在第一位的话,那就要先选一个其他城市,再选择这个城市,这个城市的区县列表才会出现。这已经够麻烦了;并且,如果是直辖市,由于没有办法选择其他城市,导致select_city的onchange事件不能触发,区县列表根本出不来。
一个解决的思路是增加一个“请选择城市”“请选择区县”这样的附加选项。但是我总觉得这种方法不够完美,呵呵。那么,还有其他更好的办法吗?