使用input标签创建复选框,type设为checkbox,配合label提升体验,name相同可分组,value提交选中值,checked设默认选中,disabled禁用选项。

在HTML中制作复选框非常简单,只需要使用 input 标签并将 type 属性设置为 checkbox 即可。复选框常用于让用户从多个选项中选择一个或多个。
基本语法
创建一个复选框的基本写法如下:
<input type="checkbox" id="option1" name="option1" value="value1"><label for="option1">选项 1</label>
说明:
- type="checkbox":定义这是一个复选框。
- id:用于唯一标识该复选框,配合 label 使用可提升点击体验。
- name:表单提交时的字段名,多个复选框可用相同 name 区分组。
- value:选中时提交的值。
- label 标签:关联后用户点击文字也能选中复选框。
多个复选框(多选场景)
当需要一组可多选的选项时,让多个复选框使用相同的 name 属性(通常加 [] 表示数组):
立即学习“前端免费学习笔记(深入)”;
<input type="checkbox" id="fruit1" name="fruits[]" value="apple"><label for="fruit1">苹果</label>
<input type="checkbox" id="fruit2" name="fruits[]" value="banana">
<label for="fruit2">香蕉</label>
<input type="checkbox" id="fruit3" name="fruits[]" value="orange">
<label for="fruit3">橙子</label>
这样在后端接收时,fruits[] 会以数组形式获取所有选中的值。
默认选中状态
如果希望某个复选框默认被选中,添加 checked 属性:
<input type="checkbox" id="agree" name="agree" value="yes" checked><label for="agree">我同意条款</label>
这个属性是布尔型,只要存在就表示选中,无需赋值。
禁用复选框
使用 disabled 属性可以让复选框不可操作:
<input type="checkbox" id="disabledOption" name="test" value="test" disabled><label for="disabledOption">不可选的选项</label>
禁用状态下不会响应点击,也不会提交值。
基本上就这些。合理使用 label、name 和 value,就能实现功能完整的复选框选择功能。实际开发中建议始终搭配 label 使用,提升可访问性和用户体验。











