#88 Dynamic Select Menus

See how to dynamically change a select menu based on another select menu using Javascript. In this episode everything is kept client side which leads to a more responsive user interface.
# javascripts_controller.rb
def dynamic_states
@states = State.find(:all)
end

# application_helper.rb
def javascript(*files)
content_for(:head) { javascript_include_tag(*files) }
end

def stylesheet(*files)
content_for(:head) { stylesheet_link_tag(*files) }
end

<!-- people/new.html.erb -->
<% javascript 'dynamic_states' %>
...
<p>
<label for="person_country_id">Country:</label>
<%= f.collection_select :country_id, Country.find(:all), :id, :name, :prompt => "Select a Country" %>
</p>
<p id="state_field">
<label for="person_state_id">State or Province:</label>
<%= f.collection_select :state_id, State.find(:all), :id, :name, :prompt => "Select a State" %>
</p>
// javascripts/dynamic_states.js.erb
var states = new Array();
<% for state in @states -%>
states.push(new Array(<%= state.country_id %>, '<%=h state.name %>', <%= state.id %>));
<% end -%>

function countrySelected() {
country_id = $('person_country_id').getValue();
options = $('person_state_id').options;
options.length = 1;
states.each(function(state) {
if (state[0] == country_id) {
options[options.length] = new Option(state[1], state[2]);
}
});
if (options.length == 1) {
$('state_field').hide();
} else {
$('state_field').show();
}
}

document.observe('dom:loaded', function() {
countrySelected();
$('person_country_id').observe('change', countrySelected);
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值