我有一个允许用户选择国家/地区的表单。根据选择的国家/地区,我需要更改州/省下拉列表以包含州列表或省份列表。我正在使用 observe_field
标签来解决这个问题,但它在 Rails 3 中被贬值了......
那么..现在应该如何处理呢?我使用 select_tag
填充下拉列表,并且 options_for_select
中使用的数组全部存储在服务器端并可在 Controller 操作中访问,因此我可以'无法从 javascript 访问它们..
最佳答案
使用卡门 gem :https://github.com/jim/carmen .
我不久前执行了以下操作(AJAX)。
HTML:
<p>
<label>Country <span>*</span></label>
<%= profile_form.select(:country,Carmen.countries, {:include_blank => 'Select a Country'}, :id => "profile_country") %>
</p>
<p>
<label>State <span>*</span></label>
<%= profile_form.select(:state, "" , {:include_blank => 'Select a Country first'}, :id => "profile_state") %>
</p>
Controller :
def states
begin
render :json => Carmen::states(CGI::unescape(params[:country]))
rescue
render :json => {"content" => "None"}.to_json
end
end
Javascript 与 jQuery:
$('#profile_country').change(function() {
if ($(this).val() == '')
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>No state provided for your country</option>'));
}
else {
$.ajax({
type: "GET",
url: "/remote/get_states/" + encodeURIComponent($(this).attr('value')),
success: function(data){
if (data.content == 'None')
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>No state provided for your country</option>'));
}
//handle the case where no state related to country selected
else
{
$('#profile_state').empty();
$('#profile_state').append( $('<option>Select your State</option>'));
jQuery.each(data,function(i, v) {
$('#profile_state').append( $('<option value="'+ data[i][1] +'">'+data[i][0] +'</option>'));
});
}
}
});
}
});
关于javascript - Rails、javascript 和更新表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5666070/