Rials实现下拉框联动的两种实现方式

本文介绍了一种基于Ajax的城市选择器实现方案,通过监听城市选择的变化并动态更新相关选项,实现了良好的用户体验。该方案使用了jQuery进行DOM操作,并通过GET请求从服务器获取新的城市列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一:partial模版替换

$(document).on('change','.change_city',function(){
var $this = $(this),
district_name = $this.find('.text').text();
if (district_name != "") {
$.ajax({
url: "/inquiry/inquiries/change_city",
type: "get",
data: {
district_name: district_name
},
success: function(data){
$this.parents('.fields').find('.city').html(data);
$(document).find('.ui.dropdown').dropdown();
}
});
}
});

def change_city
@cities = City.ind_cities(params[:district_name])||[]
render :partial => "change_city"
end

<%= select_tag "contact[inquiries][city]", options_for_select(@cities), include_blank: "City", class: "ui compact dropdown" %>


二:选择内容替换

<%= f.select :province, options_for_select(City.ind_districts, company.province), include_blank: 'Select State' %>
<%= f.select :city, options_for_select({company.city => company.city}.compact || [], company.city), include_blank: 'Select City' %>


$("#state").change(function(){
$.ajax({
type: "get",
url: '<%= get_cities_path %>',
dataType: "json",
data: {state: $('#state').val()},
success: function(data){
$("#city").html('<option value="">City </option>');
$("#city").append(data.options);
var select_comboSelect = $(document).find('select');
if (select_comboSelect.length && select_comboSelect.length > 0) {
select_comboSelect.comboSelect();
}
}
});
});

def city
options = City.ind_cities(params[:q].to_s.strip).inject(""){|options_str, c| options_str += "<option value='#{c[0]}'>#{c[1]}</option>"}
render json: {options: options}
end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值