当前位置:首页 > HTML

h5实现单选框未勾选

2026-03-06 12:24:18HTML

实现未勾选状态的单选框

在HTML5中,单选框(radio button)默认未勾选。通过HTML和CSS可以轻松实现并自定义未勾选状态。

基础HTML实现

<input type="radio" name="gender" id="male">
<label for="male">Male</label>

<input type="radio" name="gender" id="female">
<label for="female">Female</label>

自定义未勾选样式 通过CSS修改默认外观:

h5实现单选框未勾选

input[type="radio"] {
  appearance: none;
  width: 16px;
  height: 16px;
  border: 2px solid #999;
  border-radius: 50%;
  outline: none;
  margin-right: 8px;
}

input[type="radio"]:checked {
  background-color: #007bff;
}

验证必选但未勾选的情况

对于表单验证场景,当需要确保用户必须选择某项时:

HTML5 required属性

h5实现单选框未勾选

<form>
  <input type="radio" name="color" id="red" required>
  <label for="red">Red</label>

  <input type="radio" name="color" id="blue">
  <label for="blue">Blue</label>

  <button type="submit">Submit</button>
</form>

JavaScript验证

document.querySelector('form').addEventListener('submit', function(e) {
  const radios = document.querySelectorAll('input[name="color"]');
  if (![...radios].some(radio => radio.checked)) {
    e.preventDefault();
    alert('Please select an option');
  }
});

重置为未勾选状态

通过JavaScript将已选中的单选框重置:

document.getElementById('resetBtn').addEventListener('click', function() {
  const radios = document.querySelectorAll('input[name="gender"]');
  radios.forEach(radio => radio.checked = false);
});

jQuery版本

$('#resetBtn').click(function() {
  $('input[name="gender"]').prop('checked', false);
});

标签: 勾选单选框
分享给朋友:

相关文章

h5实现单选框未勾选

h5实现单选框未勾选

实现单选框未勾选状态的方法 在HTML5中,单选框(<input type="radio">)默认未勾选。若需确保初始状态为未勾选或动态控制,可通过以下方式实现: 初始未勾选状态 直接使…

react如何清除勾选

react如何清除勾选

清除勾选的方法 在React中清除勾选通常涉及状态管理和事件处理。以下是几种常见场景的解决方案。 受控组件方式 对于受控的复选框或单选按钮,通过状态控制选中状态。清除勾选只需将对应状态设为false…

react实现勾选树

react实现勾选树

实现勾选树的基本思路 使用React实现勾选树(Checkbox Tree)通常需要处理树形结构数据的渲染、勾选状态管理以及父子节点的联动逻辑。以下是具体实现方法。 安装依赖 推荐使用现成的Reac…

vue实现勾选画图

vue实现勾选画图

Vue 实现勾选画图功能 使用 Vue 和 Canvas 实现基础勾选画图 在 Vue 中实现勾选画图功能,可以通过结合 Canvas 和鼠标事件监听来实现。以下是一个基础的实现方法: 创建 Vu…

vue 实现单选框

vue 实现单选框

Vue 实现单选框的方法 在 Vue 中实现单选框可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的数据绑定功能来完成。以下是几种常见的实现方式: 使…