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

获取选中单选按钮对应下拉框值时返回undefined的问题求助

问题解决:获取选中单选按钮对应下拉框的值

问题描述

通过foreach循环生成3个单选按钮,其中2个对应Select2下拉框。点击Continue按钮时,尝试获取选中单选按钮最近的下拉框值,测试alert显示undefined。

相关代码

Razor代码

foreach (var formEType in Model.FormETypes)
{
    <div class="card mb-3">
        <div class="card-body">
            <div class="form-check d-flex align-items-center">
                @Html.RadioButtonFor(m => m.FormETypeId, formEType.FormETypeId, new { @class = "form-check-input" })
                <label class="form-check-label edit-item">
                    <b>@formEType.Name</b><br />
                    <span class="text-muted">
                        @Html.Raw(formEType.Description)
                    </span>
                </label>
            </div>
        </div>

        @if (formEType.FormETypeId != FormETypeCode.Appointment)
        {
            <div class="form-group col-md-4">
                <label class="font-weight-bold">Officer</label>
                <select name="IndividualId" class="form-control search"></select>
            </div>
        }
    </div>
}
<button class="btn btn-primary" type="button" id="continue">Continue</button>

原JavaScript代码

$('#continue').on('click', function () {
            var checkedRadio = $('input[name=FormETypeId]:checked', '#FormE');

            if (checkedRadio.val() == '@FormETypeCode.Separation' || checkedRadio.val() == '@FormETypeCode.StatusChange') {
                var closestOfficer = checkedRadio.nextAll('input').val();

                alert(closestOfficer);
            }
        });

错误原因

  1. 选择器错误:下拉框是<select>元素,不是input,原代码用nextAll('input')找不到目标元素
  2. DOM层级问题:单选按钮和下拉框不在同一直接父级下,nextAll只能查找同级元素,无法跨层级定位到下拉框

修正后的JavaScript代码

$('#continue').on('click', function () {
    var checkedRadio = $('input[name=FormETypeId]:checked', '#FormE');
    
    if (checkedRadio.length === 0) return; // 先判断是否有选中的单选按钮

    var selectedValue = checkedRadio.val();
    if (selectedValue == '@FormETypeCode.Separation' || selectedValue == '@FormETypeCode.StatusChange') {
        // 找到单选按钮所在的.card容器,再在容器内查找对应的select
        var targetSelect = checkedRadio.closest('.card').find('select[name="IndividualId"]');
        var officerValue = targetSelect.val();
        
        alert(officerValue);
    }
});

代码说明

  • closest('.card'):向上查找最近的.card父容器,确保定位到当前单选按钮所在的卡片
  • find('select[name="IndividualId"]'):在卡片容器内精准匹配目标下拉框,避免干扰其他卡片的下拉框
  • 增加checkedRadio.length === 0的判断,防止未选中任何单选按钮时触发错误逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:05:26