如何用JavaScript获取选中单选按钮的value值?
获取单选按钮的value值
你当前的代码错误在于获取了单选按钮的checked属性——这个属性本身就是用来表示按钮是否被选中的布尔值(true/false),所以自然得不到你需要的value内容。
修正后的核心代码
直接访问选中单选按钮元素的value属性即可:
let seasonType = document.querySelector('input[name="seasonType"]:checked'); // 先判断是否存在选中元素,避免无选中时触发报错 if (seasonType) { const seasonTypeVal = seasonType.value; console.log("writing out seasonTypeVal => ", seasonTypeVal); }
这段代码中,document.querySelector('input[name="seasonType"]:checked')会返回当前被选中的单选按钮DOM元素,通过.value就能直接获取到该按钮对应的value属性值(比如"spring"或"summer")。
可选:监听单选按钮选择变化
如果需要实时获取用户切换后的选中值,可以添加事件监听:
// 获取所有name为seasonType的单选按钮 const seasonRadios = document.querySelectorAll('input[name="seasonType"]'); // 给每个按钮绑定change事件 seasonRadios.forEach(radio => { radio.addEventListener('change', function() { if (this.checked) { console.log("当前选中的季节值:", this.value); } }); });
内容的提问来源于stack exchange,提问作者SkyeBoniwell
相关产品推荐
相关产品推荐

