使用radio类型实现单选,需确保同组按钮name属性相同、value不同,通过checked设置默认项,结合label提升体验,提交时仅选中项的value被发送,JavaScript可通过name获取选中值。

要实现只能单选的选项按钮,使用 HTML 中 input 元素的 radio 类型是最简单且标准的方法。关键在于正确设置 name 属性,让多个单选按钮形成一组,从而实现互斥选择。
多个 radio 按钮只有在具有相同 name 属性值时才会被视为一组,用户从中只能选择一个。
示例:
<input type="radio" name="gender" value="male"> 男 <input type="radio" name="gender" value="female"> 女 <input type="radio" name="gender" value="other"> 其他
以上三个按钮共享 name="gender",因此只能选中一个。
使用 checked 属性可以让某个选项默认被选中。
示例:
<input type="radio" name="theme" value="light" checked> 白天模式 <input type="radio" name="theme" value="dark"> 夜间模式
将 radio 与 label 关联后,点击文字也能切换选项,提升用户体验。
推荐写法:
<label> <input type="radio" name="size" value="large"> 大号 </label> <label> <input type="radio" name="size" value="medium"> 中号 </label>
当表单提交时,只有被选中的 radio 的 value 会被发送。在 JavaScript 中可通过 name 获取选中值。
JS 示例:
const selected = document.querySelector('input[name="gender"]:checked').value;
console.log(selected); // 输出 "male" 或其他选中值
注意:需确保有选项被选中,否则可能返回 null。
基本上就这些。只要 name 一致、value 不同、合理使用 label,就能实现稳定可靠的单选功能。不复杂但容易忽略细节。
以上就是如何实现只能单选的选项按钮?INPUT的radio类型使用技巧。的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号