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

文档加载时如何获取已选中的radio值,解决表单刷新后联动失效问题

问题原因

  1. 你用$('input[type=radio][name=product_type]')获取到的是包含两个同名单选按钮的jQuery对象集合,并不是当前选中的单个元素
  2. jQuery对象本身没有原生DOM的value属性,直接访问自然返回undefined,要获取选中的单选值需要加:checked筛选器,再调用jQuery的.val()方法取值。

修正后的代码

你可以直接替换你写的document.ready部分代码:

$( document ).ready(function() {
  // 先筛选出已选中的单选按钮再取值
  const selectedProductType = $('input[type=radio][name=product_type]:checked').val();
  alert(selectedProductType);
  if (selectedProductType == 'BarZero Monolithic Zirconia') {
    $("#bar_type_option").css('display', 'none');
    $('input[name="bar_type_options"]').prop('checked', false).prop("required", false);
    $("#barzero_zirconia_option").css('display', 'flex');
    $('input[name="barzero_zirconia_options"]').prop("required", true);
    $("#intaglio").css('display', 'flex');
    $('input[name="intaglio"]').prop("required", true);
  }
  else if (selectedProductType == 'BarZero Lifetime Provisional') {
    $("#barzero_zirconia_option").css('display', 'none');
    $('input[name="barzero_zirconia_options"]').prop('checked', false).prop("required", false);
    $("#intaglio").css('display', 'none');
    $('input[name="intaglio"]').prop('checked', false).prop("required", false);
    $("#bar_type_option").css('display', 'flex');
    $('input[name="bar_type_options"]').prop("required", true);
  }
});

优化建议

你当前的change事件和ready事件里的联动逻辑完全重复,可以把这部分逻辑抽成公共函数,两边都调用,减少冗余代码,后续修改也只需要改一次:

// 抽离公共的联动处理函数
function handleProductTypeChange(selectedVal) {
  if (selectedVal == 'BarZero Monolithic Zirconia') {
    $("#bar_type_option").hide();
    $('input[name="bar_type_options"]').prop({'checked': false, 'required': false});
    $("#barzero_zirconia_option").css('display', 'flex');
    $('input[name="barzero_zirconia_options"]').prop('required', true);
    $("#intaglio").css('display', 'flex');
    $('input[name="intaglio"]').prop('required', true);
  } else if (selectedVal == 'BarZero Lifetime Provisional') {
    $("#barzero_zirconia_option").hide();
    $('input[name="barzero_zirconia_options"]').prop({'checked': false, 'required': false});
    $("#intaglio").hide();
    $('input[name="intaglio"]').prop({'checked': false, 'required': false});
    $("#bar_type_option").css('display', 'flex');
    $('input[name="bar_type_options"]').prop('required', true);
  }
}

// 单选切换时触发
$("input[type=radio][name=product_type]").change(function() {
  handleProductTypeChange(this.value);
});

// 页面加载完成后触发
$(document).ready(function() {
  const selectedVal = $('input[type=radio][name=product_type]:checked').val();
  // 只有存在选中值的时候才执行联动
  if (selectedVal) {
    handleProductTypeChange(selectedVal);
  }
});

补充注意:如果页面刷新后单选按钮本身的选中状态都没保留,你需要先保证服务端渲染表单时,给已提交过的对应单选按钮加上checked属性,否则前端JS也无法获取到选中值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:45:05