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

如何用jQuery在选择主研究者后隐藏动态副研究者下拉框?

解决方案

要实现主研究者下拉框选中值后隐藏副研究者的动态下拉框,你需要调整jQuery逻辑,从禁用字段改为隐藏整个下拉框的容器元素(动态生成的下拉框通常会包裹在div或其他容器中),同时处理选中状态切换时的显示/隐藏逻辑。

假设你的ASP.NET MVC HTML结构如下(基于常规场景补充):

<div class="form-group">
    @Html.LabelFor(model => model.PrincipalInvestigatorId, "主研究者", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("PrincipalInvestigatorId", null, "请选择", htmlAttributes: new { @class = "form-control", id = "PrincipalInvestigatorId" })
        @Html.ValidationMessageFor(model => model.PrincipalInvestigatorId, "", new { @class = "text-danger" })
    </div>
</div>

<!-- 副研究者动态下拉框的容器 -->
<div id="CoInvestigatorContainer" class="form-group">
    @Html.LabelFor(model => model.CoInvestigatorId, "副研究者", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <!-- 动态生成的下拉框,假设id为CoInvestigatorId -->
        @Html.DropDownList("CoInvestigatorId", null, "请选择", htmlAttributes: new { @class = "form-control", id = "CoInvestigatorId" })
        @Html.ValidationMessageFor(model => model.CoInvestigatorId, "", new { @class = "text-danger" })
    </div>
</div>

修改后的jQuery代码:

$(document).ready(function () {
    // 初始检查:如果主研究者已选中值,默认隐藏副研究者容器
    if ($("#PrincipalInvestigatorId").val() !== "") {
        $("#CoInvestigatorContainer").hide();
    }

    // 绑定主研究者下拉框的change事件
    $("#PrincipalInvestigatorId").on("change", function () {
        var selectedValue = $(this).val();
        if (selectedValue !== "") {
            // 选中值时隐藏副研究者容器
            $("#CoInvestigatorContainer").hide();
            // 可选:同时清空副研究者的选中值,避免提交无效数据
            $("#CoInvestigatorId").val("");
        } else {
            // 未选中时显示副研究者容器
            $("#CoInvestigatorContainer").show();
        }
    });
});

关键说明:

  • 如果你是动态加载副研究者下拉框(比如通过AJAX),需要将事件委托绑定到页面始终存在的父元素上,例如:
    $("body").on("change", "#PrincipalInvestigatorId", function () {
        // 同上逻辑
    });
    
  • 隐藏容器而非仅下拉框本身,能同时隐藏标签、验证提示等关联元素,更符合完整的UI需求。
  • 清空副研究者的选中值是为了避免用户先选了副研究者,再选主研究者后,副研究者的旧值依然存在导致的提交数据异常。

内容的提问来源于stack exchange,提问作者Lucas Salomão

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:40:23