You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据前置选择项动态填充select/dropdown下拉框选项

实现国家-取还车地点级联下拉方案

核心逻辑分三步:拆分按国家映射的地点数据源、封装公共的地点选项渲染方法、在页面初始化+国家选择变更时触发渲染,同时整合原有的表单action切换逻辑。

1. 重构地点数据源

把原来写死的单一地点数组,改成按国家选择框value做key的配置映射,后续新增国家/调整地点只需要改配置即可:

// 国家与对应地点列表的映射配置
const countryLocationMap = {
  'country-1': [
    {"Id": 1, "Name": "Location - A"}, 
    {"Id": 2, "Name": "Location - B"},
    {"Id": 3, "Name": "Location - C"},
    {"Id": 4, "Name": "Location - D"},
    {"Id": 'custom', "Name": "Enter Location/Address"}
  ],
  'country-2': [
    {"Id": 1, "Name": "Location - X"},
    {"Id": 2, "Name": "Location - Y"},
    {"Id": 3, "Name": "Location - Z"}
  ]
};

2. 封装公共渲染方法

抽离独立方法处理取还车下拉框的选项渲染,逻辑包括:清空旧的非占位选项、根据选中国家追加新选项、适配Select2插件的更新触发:

/**
 * 根据传入的国家值渲染取还车地点选项
 * @param {string} countryValue 选中的国家选项value
 */
function renderLocationOptions(countryValue) {
  // 缓存两个地点下拉框的jQuery对象
  const $pickupSelect = jQuery('#cbx_reservation-form__pick-up-location-select');
  const $returnSelect = jQuery('#cbx_reservation-form__return-location-select');
  // 读取对应国家的地点列表,无匹配配置时默认用空数组
  const locationList = countryLocationMap[countryValue] || [];

  // 清空旧选项:保留默认的占位提示option,只删除动态生成的地点选项
  $pickupSelect.find('option:not([value=""][disabled][selected][hidden])').remove();
  $returnSelect.find('option:not([value=""][disabled][selected][hidden])').remove();

  // 循环追加新的地点选项
  locationList.forEach(item => {
    const optionTpl = `<option value="${item.Id}">${item.Name}</option>`;
    $pickupSelect.append(optionTpl);
    $returnSelect.append(optionTpl);
  });

  // 如果项目中使用了Select2插件,打开下面两行注释触发组件刷新
  // $pickupSelect.trigger('change');
  // $returnSelect.trigger('change');
}

3. 整合事件绑定与初始化逻辑

把原有的表单action切换逻辑和地点渲染逻辑合并到国家选择框的change事件中,同时页面首次加载时,用默认选中的国家初始化一次地点选项,避免首次进入页面下拉框为空:

jQuery(document).ready(function($) {
  const $countrySelect = $('#cbx_reservation-form__country-location-select');
  const $form = $('#cbx_reservation-form');

  // 页面初始化:读取默认选中的国家,渲染初始地点选项
  const initCountryVal = $countrySelect.val();
  renderLocationOptions(initCountryVal);

  // 绑定国家选择变更事件
  $countrySelect.on('change', function() {
    const selectedCountry = $(this).val();
    // 切换表单提交地址
    if (selectedCountry === 'country-2') {
      $form.attr('action', '/reservations-country-2/');
    } else {
      $form.attr('action', '/reservations-country-1/');
    }
    // 重新渲染对应国家的地点选项
    renderLocationOptions(selectedCountry);
  });
});

注意事项

  • 切换国家时会自动清空之前选中的取还车地点,避免出现「选了国家2但地点还是国家1的Location-A」这类非法提交值
  • 没有使用Select2插件的话,直接忽略代码里的插件刷新注释即可
  • 后续新增国家选项,只需要在countryLocationMap里添加对应国家value为key的地点数组,不需要修改事件绑定和渲染核心逻辑

内容的提问来源于stack exchange,提问作者Oudin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 16:51:43