<input type="checkbox">

checkbox 类型的 <input> 元素默认呈现为激活时选中(勾选)的框,就像你在官方政府文件表单中看到的那样。确切的外观取决于运行浏览器的操作系统配置。一般来说,这是一个正方形,但也可能有圆角。复选框允许你选择要在表单中提交(或不提交)的单个值。

¥<input> elements of type checkbox are rendered by default as boxes that are checked (ticked) when activated, like you might see in an official government paper form. The exact appearance depends upon the operating system configuration under which the browser is running. Generally this is a square but it may have rounded corners. A checkbox allows you to select single values for submission in a form (or not).

Try it

注意:单选按钮 与复选框类似,但有一个重要区别 - 同名单选按钮 被分组为一组,其中一次只能选择一个单选按钮,而复选框允许你打开和关闭单个值。当存在多个同名控件时,单选按钮允许从所有控件中选择一个,而复选框允许选择多个值。

¥Note: Radio buttons are similar to checkboxes, but with an important distinction — same-named radio buttons are grouped into a set in which only one radio button can be selected at a time, whereas checkboxes allow you to turn single values on and off. Where multiple same-named controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected.

¥Value

表示复选框值的字符串。这不会显示在客户端,但在服务器上,这是为与复选框的 name 一起提交的数据指定的 value。举个例子:

¥A string representing the value of the checkbox. This is not displayed on the client-side, but on the server this is the value given to the data submitted with the checkbox's name. Take the following example:

html
<form>
  <div>
    <input
      type="checkbox"
      id="subscribeNews"
      name="subscribe"
      value="newsletter" />
    <label for="subscribeNews">Subscribe to newsletter?</label>
  </div>
  <div>
    <button type="submit">Subscribe</button>
  </div>
</form>

在此示例中,我们的名称为 subscribe,值为 newsletter。提交表单时,数据名称/值对将为 subscribe=newsletter

¥In this example, we've got a name of subscribe, and a value of newsletter. When the form is submitted, the data name/value pair will be subscribe=newsletter.

如果省略 value 属性,则该复选框的默认值为 on,因此在这种情况下提交的数据将为 subscribe=on

¥If the value attribute was omitted, the default value for the checkbox is on, so the submitted data in that case would be subscribe=on.

注意:如果提交表单时未选中复选框,则名称和值都不会提交到服务器。没有纯 HTML 方法来表示复选框的未选中状态(例如 value=unchecked)。如果你想在未选中复选框时提交默认值,你可以包含 JavaScript 以在表单中创建一个 <input type="hidden">,其值指示未选中状态。

¥Note: If a checkbox is unchecked when its form is submitted, neither the name nor the value is submitted to the server. There is no HTML-only method of representing a checkbox's unchecked state (e.g. value=unchecked). If you wanted to submit a default value for the checkbox when it is unchecked, you could include JavaScript to create a <input type="hidden"> within the form with a value indicating an unchecked state.

附加属性

¥Additional attributes

除了所有 <input> 元素共享的 共同属性 之外,“checkbox”输入还支持以下属性。

¥In addition to the common attributes shared by all <input> elements, "checkbox" inputs support the following attributes.

checked

boolean 属性,指示默认情况下(页面加载时)是否选中此复选框。它并不指示当前是否选中此复选框:如果复选框的状态发生更改,则此内容属性不会反映更改。(仅更新 HTMLInputElementchecked IDL 属性。)

注意:与其他输入控件不同,如果复选框当前为 checked,则该复选框的值仅包含在提交的数据中。如果是,则将复选框的 value 属性的值报告为输入值,如果未设置 value,则报告为 on。与其他浏览器不同,Firefox 默认情况下会跨页面加载 保持动态检查状态<input>。使用 autocomplete 属性来控制此功能。

¥Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked. If it is, then the value of the checkbox's value attribute is reported as the input's value, or on if no value is set. Unlike other browsers, Firefox by default persists the dynamic checked state of an <input> across page loads. Use the autocomplete attribute to control this feature.

value

value 属性是所有 <input> 共享的属性;然而,它对于 checkbox 类型的输入有特殊用途:提交表单时,仅将当前选中的复选框提交给服务器,报告的值为 value 属性的值。如果不另外指定 value,则默认为字符串 on。这在上面的 节中得到了证明。

使用复选框输入

¥Using checkbox inputs

我们已经在上面介绍了复选框最基本的用法。现在让我们看看你需要的其他常见的与复选框相关的功能和技术。

¥We already covered the most basic use of checkboxes above. Let's now look at the other common checkbox-related features and techniques you'll need.

处理多个复选框

¥Handling multiple checkboxes

我们上面看到的示例仅包含一个复选框;在现实世界中,你可能会遇到多个复选框。如果它们完全不相关,那么你可以单独处理它们,如上所示。然而,如果它们都是相关的,事情就不是那么简单了。

¥The example we saw above only contained one checkbox; in real-world situations you'll be likely to encounter multiple checkboxes. If they are completely unrelated, then you can just deal with them all separately, as shown above. However, if they're all related, things are not quite so simple.

例如,在下面的演示中,我们包含多个复选框以允许用户选择他们的兴趣(请参阅 示例 部分中的完整版本)。

¥For example, in the following demo we include multiple checkboxes to allow the user to select their interests (see the full version in the Examples section).

html
<fieldset>
  <legend>Choose your interests</legend>
  <div>
    <input type="checkbox" id="coding" name="interest" value="coding" />
    <label for="coding">Coding</label>
  </div>
  <div>
    <input type="checkbox" id="music" name="interest" value="music" />
    <label for="music">Music</label>
  </div>
</fieldset>

在此示例中,你将看到我们为每个复选框指定了相同的 name。如果两个复选框都被选中,然后提交表单,你将得到一串名称/值对,如下所示:interest=coding&interest=music。当该字符串到达服务器时,你需要将其解析为关联数组以外的方式,因此 interest 的所有值(而不仅仅是最后一个值)都会被捕获。例如,有关 Python 使用的一项技术,请参阅 使用单个服务器端变量处理多个复选框

¥In this example you will see that we've given each checkbox the same name. If both checkboxes are checked and then the form is submitted, you'll get a string of name/value pairs submitted like this: interest=coding&interest=music. When this string reaches the server, you need to parse it other than as an associative array, so all values, not only the last value, of interest are captured. For one technique used with Python, see Handle Multiple Checkboxes with a Single Serverside Variable, for example.

默认选中复选框

¥Checking boxes by default

要使复选框默认处于选中状态,请为其指定 checked 属性。请参阅下面的示例:

¥To make a checkbox checked by default, you give it the checked attribute. See the below example:

html
<fieldset>
  <legend>Choose your interests</legend>
  <div>
    <input type="checkbox" id="coding" name="interest" value="coding" checked />
    <label for="coding">Coding</label>
  </div>
  <div>
    <input type="checkbox" id="music" name="interest" value="music" />
    <label for="music">Music</label>
  </div>
</fieldset>

为你的复选框提供更大的点击区域

¥Providing a bigger hit area for your checkboxes

在上面的示例中,你可能已经注意到,可以通过单击关联的 <label> 元素以及复选框本身来切换复选框。这是 HTML 表单标签的一个非常有用的功能,可以让你更轻松地单击所需的选项,尤其是在智能手机等小屏幕设备上。

¥In the above examples, you may have noticed that you can toggle a checkbox by clicking on its associated <label> element as well as on the checkbox itself. This is a really useful feature of HTML form labels that makes it easier to click the option you want, especially on small-screen devices like smartphones.

除了可访问性之外,这是在表单上正确设置 <label> 元素的另一个好理由。

¥Beyond accessibility, this is another good reason to properly set up <label> elements on your forms.

不确定状态复选框

¥Indeterminate state checkboxes

除了选中和未选中状态之外,复选框还可以处于第三种状态:不定。在这种状态下,无法判断该项目是打开还是关闭。这是通过 JavaScript 使用 HTMLInputElement 对象的 indeterminate 属性来设置的(不能使用 HTML 属性来设置):

¥In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the HTMLInputElement object's indeterminate property via JavaScript (it cannot be set using an HTML attribute):

js
inputInstance.indeterminate = true;

处于不确定状态的复选框在框中有一条水平线(看起来有点像连字符或减号),而不是大多数浏览器中的复选/勾号。

¥A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers.

该属性的用例并不多。最常见的是当复选框可用时,"owns" 有多个子选项(也是复选框)。如果选中所有子选项,则也会选中所属复选框,如果全部未选中,则也会取消选中所属复选框。如果任何一个或多个子选项的状态与其他子选项不同,则所属复选框处于不确定状态。

¥There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked, and if they're all unchecked, the owning checkbox is unchecked. If any one or more of the sub-options have a different state than the others, the owning checkbox is in the indeterminate state.

这可以在下面的例子中看到(感谢 CSS 技巧 的启发)。在此示例中,我们跟踪为秘诀收集的成分。当你选中或取消选中某个成分的复选框时,JavaScript 函数会检查选中的成分总数:

¥This can be seen in the below example (thanks to CSS Tricks for the inspiration). In this example we keep track of the ingredients we are collecting for a recipe. When you check or uncheck an ingredient's checkbox, a JavaScript function checks the total number of checked ingredients:

  • 如果未选中任何一项,则配方名称的复选框将设置为未选中。
  • 如果选中一两个,则配方名称的复选框将设置为 indeterminate
  • 如果全部三个都被选中,则配方名称的复选框将设置为 checked

因此,在本例中,indeterminate 状态用于表示已开始收集原料,但配方尚未完成。

¥So in this case the indeterminate state is used to state that collecting the ingredients has started, but the recipe is not yet complete.

js
const overall = document.querySelector("#enchantment");
const ingredients = document.querySelectorAll("ul input");

overall.addEventListener("click", (e) => {
  e.preventDefault();
});

for (const ingredient of ingredients) {
  ingredient.addEventListener("click", updateDisplay);
}

function updateDisplay() {
  let checkedCount = 0;
  for (const ingredient of ingredients) {
    if (ingredient.checked) {
      checkedCount++;
    }
  }

  if (checkedCount === 0) {
    overall.checked = false;
    overall.indeterminate = false;
  } else if (checkedCount === ingredients.length) {
    overall.checked = true;
    overall.indeterminate = false;
  } else {
    overall.checked = false;
    overall.indeterminate = true;
  }
}

注意:如果你提交带有不确定复选框的表单,则会发生与未选中该复选框相同的情况 - 不会提交任何数据来表示该复选框。

¥Note: If you submit a form with an indeterminate checkbox, the same thing happens as if the checkbox were unchecked — no data is submitted to represent the checkbox.

验证

¥Validation

复选框确实支持 validation(提供给所有 <input>)。然而,大多数的 ValidityState 永远是 false。如果复选框具有 required 属性,但未选中,则 ValidityState.valueMissing 将是 true

¥Checkboxes do support validation (offered to all <input>s). However, most of the ValidityStates will always be false. If the checkbox has the required attribute, but is not checked, then ValidityState.valueMissing will be true.

示例

¥Examples

以下示例是我们上面看到的 "多个复选框" 示例的扩展版本 - 它具有更多标准选项,加上 "other" 复选框,选中该复选框后会出现一个文本字段,用于输入 "other" 选项的值。这是通过一个简单的 JavaScript 块来实现的。该示例包含隐式标签,其中 <input> 直接位于 <label> 内。没有可见标签的文本输入包含提供其可访问名称的 aria-label 属性。此示例还包含一些 CSS 来改进样式。

¥The following example is an extended version of the "multiple checkboxes" example we saw above — it has more standard options, plus an "other" checkbox that when checked causes a text field to appear to enter a value for the "other" option. This is achieved with a simple block of JavaScript. The example includes implicit labels, with the <input> directly inside the <label>. The text input, without a visible label, includes the aria-label attribute which provides its accessible name. This example also includes some CSS to improve the styling.

HTML

html
<form>
  <fieldset>
    <legend>Choose your interests</legend>
    <div>
      <label>
        <input type="checkbox" id="coding" name="interest" value="coding" />
        Coding
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="music" name="interest" value="music" />
        Music
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="art" name="interest" value="art" />
        Art
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="sports" name="interest" value="sports" />
        Sports
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="cooking" name="interest" value="cooking" />
        Cooking
      </label>
    </div>
    <div>
      <label>
        <input type="checkbox" id="other" name="interest" value="other" />
        Other
      </label>
      <input
        type="text"
        id="otherValue"
        name="other"
        aria-label="Other interest" />
    </div>
    <div>
      <button type="submit">Submit form</button>
    </div>
  </fieldset>
</form>

CSS

css
html {
  font-family: sans-serif;
}

form {
  width: 600px;
  margin: 0 auto;
}

div {
  margin-bottom: 10px;
}

fieldset {
  background: cyan;
  border: 5px solid blue;
}

legend {
  padding: 10px;
  background: blue;
  color: cyan;
}

JavaScript

js
const otherCheckbox = document.querySelector("#other");
const otherText = document.querySelector("#otherValue");
otherText.style.visibility = "hidden";

otherCheckbox.addEventListener("change", () => {
  if (otherCheckbox.checked) {
    otherText.style.visibility = "visible";
    otherText.value = "";
  } else {
    otherText.style.visibility = "hidden";
  }
});

技术总结

¥Technical summary

表示复选框值的字符串。
活动 change and input
支持的通用属性 checked
IDL 属性 checkedindeterminatevalue
DOM 接口

HTMLInputElement

方法 select()
隐式 ARIA 角色 checkbox

规范

Specification
HTML Standard
# checkbox-state-(type=checkbox)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also