如何选中单个radio选项?纯HTML单选全选问题求助
解决HTML单选框(radio)全选问题
问题的核心原因是:同一组的单选框必须共享完全相同的name属性值,浏览器才会将它们识别为互斥选项。如果每个radio的name不同或未设置,就会被当成独立选项,导致可以同时选中多个。
错误示例(会出现全选问题)
<input type="radio" id="opt1" name="option1" value="1"> <label for="opt1">选项1</label> <input type="radio" id="opt2" name="option2" value="2"> <label for="opt2">选项2</label> <input type="radio" id="opt3" name="option3" value="3"> <label for="opt3">选项3</label> <input type="radio" id="opt4" name="option4" value="4"> <label for="opt4">选项4</label>
正确示例(实现互斥选中)
将所有radio的name设置为同一个值(比如"choices"):
<input type="radio" id="opt1" name="choices" value="1"> <label for="opt1">选项1</label> <input type="radio" id="opt2" name="choices" value="2"> <label for="opt2">选项2</label> <input type="radio" id="opt3" name="choices" value="3"> <label for="opt3">选项3</label> <input type="radio" id="opt4" name="choices" value="4"> <label for="opt4">选项4</label>
额外说明
id属性只需保证唯一,用来和<label>的for关联,不影响互斥逻辑,点击标签就能选中对应radio。- 若要默认选中某个选项,给对应radio添加
checked属性即可,例如:<input type="radio" id="opt1" name="choices" value="1" checked>
内容的提问来源于stack exchange,提问作者Wisdom
相关产品推荐
相关产品推荐

