如何获取选中input的value?遇Uncaught TypeError错误求助
问题分析与解决
错误原因
你遇到的Uncaught TypeError: Cannot read properties of null (reading 'value'),本质是input变量的值为null,访问它的value属性自然会报错。
出现这个问题的核心原因:
- 你在页面初始化时就执行了
document.querySelector('input[name="num"]:checked'),但此时页面中可能没有任何单选框被选中,导致获取到的结果是null。 - 即便初始化时有选中项,用户在点击按钮前切换选中项的话,之前保存的
input引用也不会自动更新,依然可能指向已取消选中的元素。
修复方案
把获取选中单选框的逻辑移到按钮点击事件内部,同时增加判空处理,确保每次点击都能拿到当前最新的选中项:
const button = document.getElementById('button'); button.addEventListener('click', () => { // 每次点击时重新获取当前选中的单选框 const input = document.querySelector('input[name="num"]:checked'); // 先判断是否有选中项,避免报错 if (!input) { console.log('请先选择一个选项'); return; } console.log(input.value); // 修正原代码的逻辑错误:应该是把选中值赋值给output,而非反过来 document.getElementById('output').innerHTML = input.value; const before = document.getElementById('before'); const after = document.getElementById('after'); before.style.display = 'none'; after.style.display = 'flex'; });
额外注意事项
- 检查单选框的
name属性是否确实为num,拼写错误会导致querySelector找不到元素。 - 确保JS代码在DOM加载完成后执行:可以把脚本标签放在HTML的
</body>标签之前,或者用DOMContentLoaded事件包裹代码,避免因DOM未加载完成导致获取不到元素:
document.addEventListener('DOMContentLoaded', () => { const button = document.getElementById('button'); button.addEventListener('click', () => { const input = document.querySelector('input[name="num"]:checked'); if (!input) { console.log('请先选择一个选项'); return; } console.log(input.value); document.getElementById('output').innerHTML = input.value; const before = document.getElementById('before'); const after = document.getElementById('after'); before.style.display = 'none'; after.style.display = 'flex'; }); });
内容的提问来源于stack exchange,提问作者Carla
相关产品推荐
相关产品推荐

