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

如何获取被Div分隔的Radio Button选中值?

嘿,我来帮你搞定这个问题!

问题分析

你遇到的ReferenceError: editList is not defined错误原因很直接:editList是你给radio按钮设置的name属性值,并不是一个可以直接调用的全局变量或DOM元素,浏览器找不到这个变量,所以抛出了错误。而且你完全不用改动当前的div分隔布局,只需要调整JS代码就能正确获取选中值。

解决方案(保持布局不变)

这里有两种可靠的方法,都能完美适配你现有的布局:

方法1:使用document.querySelector(推荐,最简洁)

直接通过CSS选择器定位到被选中的radio按钮:

document.getElementById("submitButton").onclick = function(){
  // 定位name为editList且被勾选的radio
  const selectedRadio = document.querySelector('input[name="editList"]:checked');
  
  // 先判断是否有选中项,避免空值报错
  if(selectedRadio){
    const selectedValue = selectedRadio.value;
    console.log(selectedValue);
  } else {
    console.log("请先选择一个选项哦!");
  }
}

方法2:使用document.getElementsByName(遍历方式)

如果你习惯通过遍历所有radio来找到选中项,可以用这个方法:

document.getElementById("submitButton").onclick = function(){
  const radioButtons = document.getElementsByName("editList");
  let selectedValue = null;
  
  // 遍历所有radio,找到被选中的那个
  for(let i = 0; i < radioButtons.length; i++){
    if(radioButtons[i].checked){
      selectedValue = radioButtons[i].value;
      break;
    }
  }
  
  if(selectedValue){
    console.log(selectedValue);
  } else {
    console.log("请选择一个选项");
  }
}
额外的小修复(提升用户体验)

你的HTML里还有两个小细节问题,虽然不影响获取值,但会影响交互体验:

  • 所有radio的value都设成了"always",这会导致不管选哪个选项,输出的都是同一个值,建议改成对应选项的标识:
    <input id="radButLinear" type="radio" name="editList" value="linear" class="radioInputStyle"/>
    <input id="radButTactile" type="radio" name="editList" value="tactile" class="radioInputStyle"/>
    <input id="radButTandC" type="radio" name="editList" value="tactile-clicky" class="radioInputStyle"/>
    
  • label的for属性应该对应radio的id,而不是"always",这样点击label文字就能选中对应的radio:
    <label for="radButLinear" class="radioLabelStyle">Linear</label>
    <label for="radButTactile" class="radioLabelStyle">Tactile</label>
    <label for="radButTandC" class="radioLabelStyle">Tactile and Clicky</label>
    

内容的提问来源于stack exchange,提问作者J. Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:04:07