有国家,州和城市的三个下拉框。
.entry.float
%label{:for => "hospital-country"} Country
= select_tag :country_id, options_for_select(["Select option"] + @countries.collect{ |c| [c.name, c.id] },@hospital.country_id),{:name =>"hospital[country_id]",:class => "select r5",:id => "hospital-country",:onchange=>"country_change()"}
.entry.float
%label{:for => "hospital-state"} State
= select_tag :state, options_for_select(["Select option"]),{:name =>"hospital[state]",:id => 'hospital-state',:class => "select r5",:disabled => true,:onchange=>"state_change()"}
.entry.float
%label{:for => "hospital-city"} City
= select_tag :city, options_for_select(["Select option"]),{:name =>"hospital[city]",:id => 'hospital-city',:class => "select r5",:disabled => true}
`在哪个国家/地区居住
@countries = WorldCountry.all
` 和 state 和 city 分别使用 jquery 由国家和 state 下拉框的 ajax 调用填充
function country_change() {
$('#hospital-state').find('option[value!="Select option"]').remove();
$('#hospital-state').next().text("Select option");
$('#hospital-state').attr('disabled', 'disabled');
$('#hospital-city').find('option[value!="Select option"]').remove();
$('#hospital-city').next().text("Select option");
$('#hospital-city').attr('disabled', 'disabled');
if ($('#hospital-country').val() != "" && $('#hospital-country').val() != "Select option") {
$.ajax({
type : 'post',
url : '/hospitals/country_change',
data : {
country_id : $('#hospital-country').val()
},
dataType : "json",
success : function(data) {
var select = $('#hospital-state');
if (data.length > 0) {
select.removeAttr('disabled');
$.each(data, function(key, value) {
$("<option/>").val(value[1]).text(value[0]).appendTo(select);
});
}
},
failure : function() {
}
})
}
};
这一切都在起作用。但是当验证失败时,我只能保留国家的价值。如何保留仅在 ajax 中有效的 State 和 Cities 的值。