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

父选项变更后子下拉列表未重置选中值的JS解决方案求助

解决方案:父下拉框切换后重置子下拉框选中值

嘿,我明白你的问题了——当你切换父下拉框(issue_field_72)的选项后,子下拉框(issue_field_73)还保留着之前选中的、现在已经被禁用或隐藏的选项值,对吧?这是因为你的现有代码只处理了子选项的显示与禁用状态,但没有在父选项变更时重置子下拉框的选中状态。

修改后的完整代码

$(function() {
  var parentFieldId = 'issue_field_72';
  var childFieldId = 'issue_field_73';
  var isTarget = function(child, parent) {
    return child.text().indexOf(parent.text()) == 0;
  }
  var narrowChildField = function() {
    var parentSelected = $('#' + parentFieldId + ' > option:selected');
    $('#' + childFieldId + ' > option').each(function() {
      var child = $(this);
      if (isTarget(child, parentSelected)) {
        child.show();
        child.prop('disabled', false);
      } else {
        child.hide();
        child.prop('disabled', true);
      }
    });

    // 新增:重置子下拉框的选中状态
    var childSelect = $('#' + childFieldId);
    var currentSelected = childSelect.find('option:selected');
    // 如果当前选中的选项是禁用状态或不可见,就重置到默认空选项
    if (currentSelected.prop('disabled') || currentSelected.is(':hidden')) {
      childSelect.val('');
    }
  }
  narrowChildField();
  $('#all_attributes').change(function(e) {
    if (e.target.id == parentFieldId) {
      narrowChildField();
    }
  });
  var _replaceIssueFormWith = replaceIssueFormWith;
  replaceIssueFormWith = function(html){
    _replaceIssueFormWith(html);
    narrowChildField();
  };
});

关键改动说明

在narrowChildField函数末尾新增了重置逻辑:

  • 先获取子下拉框的DOM对象childSelect
  • 定位当前选中的选项currentSelected
  • 检查该选项是否处于禁用(disabled)或隐藏(:hidden)状态,若满足任一条件,就将子下拉框的值设为空(对应默认的「--- Please select ---」选项)

这样修改后,切换父下拉框选项时,子下拉框会自动清空之前的无效选中值,用户必须重新选择符合当前父选项的子选项,就能解决你遇到的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:19:10