<input>
elements of type checkbox
are rendered by default as square boxes that are checked (ticked) when activated, like you might see in an official government paper form. They allow you to select single values for submission in a form (or not).
The source for this interactive example is stored in a GitHub repository. If you’d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Value | A DOMString representing the value of the checkbox. |
Events | change and input |
Supported common attributes | checked |
IDL attributes | checked and value |
Methods | select() |
Value
A DOMString
representing the value of the checkbox. This is never seen 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:
<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>
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
.
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
.
Additional attributes
In addition to the common attributes shared by all <input>
elements, "checkbox"
inputs support the following attributes:
Attribute | Description |
---|---|
checked |
Boolean; if present, the checkbox is currently toggled on |
value |
The string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on |
checked
A Boolean attribute indicating whether or not this checkbox is currently selected (checked).
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
The value
attribute is one which all inputs share; however, it serves a special purpose for inputs of type checkbox
: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value
attribute. If the
value
is not otherwise specified, it is the string "on"
by default. This is demonstrated in the section Value above.
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).
<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>
In this example you will see that we’ve given each checkbox the same name
(note the brackets at the end of the name, which allows the values to be sent as an array). 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 data reaches the server-side, you should be able to capture it as an array of related values and deal with it appropriately — see Handle Multiple Checkboxes with a Single Serverside Variable, for example.
Checking boxes by default
To make a checkbox checked by default, you simply give it the checked
attribute. See the below example:
<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
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.
Beyond accessibility, this is another good reason to properly set up <label>
elements on your forms.
Indeterminate state checkboxes
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):
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.
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.
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:
- If none are checked, the recipe name’s checkbox is set to unchecked.
- If one or two are checked, the recipe name’s checkbox is set to
indeterminate
. - If all three are checked, the recipe name’s checkbox is set to
checked
.
So in this case the indeterminate
state is used to state that collecting the ingredients has started, but the recipe is not yet complete.
var overall = document.querySelector('input[id="EnchTbl"]'); var ingredients = document.querySelectorAll('ul input'); overall.addEventListener('click', function(e) { e.preventDefault(); }); for(var i = 0; i < ingredients.length; i++) { ingredients[i].addEventListener('click', updateDisplay).
; } }
Validation
Checkboxes do support validation (offered to all <input>
s). However, most of the ValidityState
s will always be false
. If the checkbox has the required
attribute, but is not checked, then ValidityState.valueMissing
will be true
.
Examples
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 also includes some CSS to improve the styling.
HTML
<form> <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> <div> <input type="checkbox" id="art" name="interest" value="art"> <label for="art">Art</label> </div> <div> <input type="checkbox" id="sports" name="interest" value="sports"> <label for="sports">Sports</label> </div> <div> <input type="checkbox" id="cooking" name="interest" value="cooking"> <label for="cooking">Cooking</label> </div> <div> <input type="checkbox" id="other" name="interest" value="other"> <label for="other">Other</label> <input type="text" id="otherValue" name="other"> </div> <div> <button type="submit">Submit form</button> </div> </fieldset> </form>
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
var otherCheckbox = document.querySelector('input[value="other"]'); var otherText = document.querySelector('input[id="otherValue"]'); otherText.style.visibility = 'hidden'; otherCheckbox.onchange = function() { if(otherCheckbox.checked) { otherText.style.visibility = 'visible'; otherText.value = ''; } else { otherText.style.visibility = 'hidden'; } };
Specifications
Specification | Status | Comment |
HTML Living Standard The definition of ‘<input type=»checkbox»>’ in that specification. |
Living Standard | |
HTML5 The definition of ‘<input type=»checkbox»>’ in that specification. |
Recommendation |
developer.mozilla.org
В последнее время сложилось ощущение, что много людей пишет про создание табов (вкладок) на CSS.
Сейчас я хочу рассказать про ещё один способ создания вкладок на CSS (Предупреждая выпады в свою сторону, упомяну, что без :target).

Но обо всём по порядку.
:checked или немного теории
Итак, в CSS3 (В модуле css3-selectors) появился новый псевдокласс :checked.
Вкратце, этот псевдокласс применяется к тем input’ам (checkbox или radiobutton), которые выставлены пользователем в состояние выбора (checked).
Табы, табы, табы
Довольно много реализаций табов было описано (Например, вот тут сделано через поле input type=«text» выставленное в readonly), но в большинстве своём они опирались на псевдокласс :target, чьё использование немного неоправданно из-за «прыгающего» контента.
Из-за чего была придумана сверхпростая реализация вкладок при помощи :checked и радиобаттонов.
Дабы не перегружать читателя кодом, я урезал пример с 4 вкладок до 2, полный пример доступен тут
HTML:
<section> <input type="radio" id="tab1" name="radiobutton" checked="checked"/> <label for="tab1" class="tabs">qutIM 0.1</label> <input type="radio" id="tab2" name="radiobutton"/> <label for="tab2" class="tabs">qutIM 0.2</label> <article> qutIM 0.1 — Однопротокольный клиент, вышедший в 2008 году. </article> <article> qutIM 0.2 — Многопротокольный клиент, вышедший в 2010 году. </article> </section>
CSS:
input { display: none; } input:checked + label { background: #CCC; } input:checked + label + input + label + article { /* Страшно? */ display: block; } input:checked + label + article + article { display: block; } article { display: none; }
Сей код лишён всех лишних стилей, дабы не мешать пониманию.
Отдельно хочу сказать, что это лишь пример, что можно сделать при помощи CSS и HTML, ибо использование сего в реальных сайтах затруднительно и вот почему:
Сей код корректно работает в Firefox, Opera, IE9+, но не работает в Webkit-браузерах. а вот тут я немного поспешил.
WebKit не обновляет значение до изменения кода, но его можно принудительно заставить это делать, добавив весьма грязный хак:
section { -webkit-animation: 0.1s hack infinite; } @-webkit-keyframes hack { from {margin: 0; padding: 0;} to {margin: 0; padding: 0;} }
Анимация, которая ничего не делает. Вебкит не перестаёт удивлять.
Как вы заметили, я неоднократно воспользовался свойством селектора следующего элемента, который, в общем-то, не рекомендуется к использованию по причинам производительности. Но чуть ниже я покажу такое использование этого селектора, что и не снилось.
Немного бреда
А что, если использовать чекбоксы для ввода двоичных чисел?
Берём два чекбокса, располагаем последовательно и делаем что-то вроде:
input + div::after { content: "0"; } input:checked + div::after { content: "1"; } input:checked + input + div::after { content: "2"; } input:checked + input:checked + div::after { content: "3"; }
Бред? Сумасшествие? Троллейбус.jpg? На самом деле, всего-лишь демонстрация и немного свободного времени.
К слову, за полчаса был написан вот такой небольшой скриптик, генерирующий стиль (Аналогичный вышенаписанному) и строчку из чекбоксов для перевода из двоичной системы в десятеричную 🙂
Немного погодя был написан аналогичный скрипт, генерирующий аналогичный стиль, но для перевода из троичных чисел в десятеричные.
В HTML существуют tri-state чекбоксы, но для их создания требуется javascript (для выставления элементу indeterminate = true), а так же есть псевдокласс :indeterminate по аналогии с :checked.
Разумеется, и речи не идёт где-то это применять вот таким методом. Всё это приводится как информация к размышлению.
А ещё?
Вот здесь можно почитать заметку за авторством kizu про выпадающие менюшки, основанные на том же принципе.
habr.com
Code Example
<form> <input type="checkbox" name="love" value="love" id="love"><label for="love"> Check if you love this website!</label> </form>
Handling checkbox data
Checkboxes are a little unwieldy from a data standpoint. Part of this is that there are essentially two different ways to think about their functionality. Frequently, a set of checkboxes represents a single question which the user can answer by selecting any number of possible answers. They are, importantly, not exclusive of each other. (If you want the user to only be able to pick a single option, use radio boxes or the <select>
element.)
<form> <p>Check all the languages you have proficiency in.</p> <input type="checkbox" id="HTML" value="HTML"><label for="HTML"> HTML</label><br> <input type="checkbox" id="CSS" value="CSS"><label for="CSS"> CSS</label><br> <input type="checkbox" id="JS" value="JS"><label for="JS"> JS</label><br> <input type="checkbox" id="PHP" value="PHP"><label for="PHP"> PHP</label><br> <input type="checkbox" id="Ruby" value="Ruby"><label for="Ruby"> Ruby</label><br> <input type="checkbox" id="INTERCAL" value="INTERCAL"><label for="INTERCAL"> INTERCAL</label><br> </form>
The natural way to represent this in you application code (server-side or front-end) is with an array.
userLangs = ['HTML', 'CSS', 'INTERCAL']
However, that isn’t how the browser will send the data. Rather, the browser treats a checkbox as if it is always being used the other way, as a boolean truth value.
<input type="checkbox" name="tandc" id="tandc" value="true"><label for="tandc"> I agree to all terms and conditions.</label>
Unlike with radio buttons, a set of checkboxes are not logically tied together in the code. So from HTML’s point of view, each checkbox in a set of checkboxes is essentially on its own. This works perfectly for single-choice boolean value checkboxes, but it presents a little hiccup for arrays of choices. There are two ways to deal with it. You can either give all the checkboxes the same name
attribute, or you can give each one a different name
.
<!-- All the same name attribute. --> <form> <p>Check all the languages you have proficiency in.</p> <input type="checkbox" id="HTML" value="HTML" name="langs"><label for="HTML"> HTML</label><br> <input type="checkbox" id="CSS" value="CSS" name="langs"><label for="CSS"> CSS</label><br> <input type="checkbox" id="JS" value="JS" name="langs"><label for="JS"> JS</label><br> <input type="checkbox" id="PHP" value="PHP" name="langs"><label for="PHP"> PHP</label><br> <input type="checkbox" id="Ruby" value="Ruby" name="langs"><label for="Ruby"> Ruby</label><br> <input type="checkbox" id="INTERCAL" value="INTERCAL" name="langs"><label for="INTERCAL"> INTERCAL</label><br> </form> <!-- Different name attributes. --> <form> <p>Check all the languages you have proficiency in.</p> <input type="checkbox" id="HTML" value="HTML" name="HTML"><label for="HTML"> HTML</label><br> <input type="checkbox" id="CSS" value="CSS" name="CSS"><label for="CSS"> CSS</label><br> <input type="checkbox" id="JS" value="JS" name="JS"><label for="JS"> JS</label><br> <input type="checkbox" id="PHP" value="PHP" name="PHP"><label for="PHP"> PHP</label><br> <input type="checkbox" id="Ruby" value="Ruby" name="Ruby"><label for="Ruby"> Ruby</label><br> <input type="checkbox" id="INTERCAL" value="INTERCAL" name="INTERCAL"><label for="INTERCAL"> INTERCAL</label><br> </form>
If you use the same name
for all, your request string will look like this: langs=HTML&langs=CSS&langs=PHP
If you use different names, it looks like this: HTML=HTML&CSS=CSS&PHP=PHP
The first one seems a bit preferable, but what happens when you get to PHP and try to get the values?
$langs = $_REQUEST['langs']; // What is $langs ?
In PHP, you can make sure that the various identically-named checkboxes are combined into an array on the server by appending a set of square brackets ([]
) after the name.
<form> <p>Check all the languages you have proficiency in.</p> <input type="checkbox" id="HTML" value="HTML" name="langs[]"><label for="HTML"> HTML</label><br> <input type="checkbox" id="CSS" value="CSS" name="langs[]"><label for="CSS"> CSS</label><br> <input type="checkbox" id="JS" value="JS" name="langs[]"><label for="JS"> JS</label><br> <input type="checkbox" id="PHP" value="PHP" name="langs[]"><label for="PHP"> PHP</label><br> <input type="checkbox" id="Ruby" value="Ruby" name="langs[]"><label for="Ruby"> Ruby</label><br> <input type="checkbox" id="INTERCAL" value="INTERCAL" name="langs[]"><label for="INTERCAL"> INTERCAL</label><br> </form>
See this PHP forms tutorialfor more information. This array-making syntax is actually a feature of PHP, and not HTML. If you are using a different server side, you may have to do things a little differently. (Thankfully, if you are using something like Rails or Django, you probably will use some form builder classes and not have to worry about the markup as much.)
Good labelling practices
You should always put the <label>
after the <input type="checkbox">
, and on the same line. There should usually be a space between the <input>
and the <label>
. You can accomplish this with a little bit of margin, or with simply a typographical space. The <label>
should always use for
attribute, which specifies that it is connected to the <input>
by id
. This is an important usability practice, as it allows the user to check and uncheck the box by clicking the label, not just the (too small) checkbox itself. This is even more critical today than it was in the past because of touchscreens — you want to give the user the easiest possible checkbox experience.
<form> <input type="checkbox" id="yes"><label for="yes"> Yes! Do it this way.</label><br> <br> <input type="checkbox" id="no1"><label for="no1">No. This needs space between the box and the words.</label><br> <br> <label for="no2">No. The checkbox should come before the label. </label><input type="checkbox" id="no2"><br> <br> <input type="checkbox" id="no-label"><label> No. The label needs to identify the checkbox.</label><br> <label for="no3">Do you like it this way? (Wrong.)</label><br> <input type="checkbox" id="no3"><br>
It’s amazing how much of a difference little details like that make to the way your user experiences and feels about your site. You want to make your users happy to use your forms, or at least not hate them. Proper form styling and usability go a long way to improving the overall satisfaction your users experience. For more information, see our tutorials on form styling and form usability.
html.com
Стоимость
DOMString
представляющий значение флажка. Это никогда не наблюдается на стороне клиента, но на сервере это value
данное данным, представленным с name
флажка. Возьмем следующий пример:
<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
.
Если атрибут value
был опущен, значение по умолчанию для этого флажка включено, поэтому представленные данные в этом случае будут subscribe=on
.
Использование входов флажка
Мы уже рассмотрели самое основное использование флажков выше. Давайте теперь рассмотрим другие общие функции и методы, связанные с флажком, которые вам понадобятся.
Обработка нескольких флажков
Пример, который мы видели выше, содержит только один флажок; в реальных ситуациях вы, вероятно, столкнетесь с несколькими флажками. Если они полностью не связаны друг с другом, вы можете просто разобраться с ними все отдельно, как показано выше. Однако, если все они связаны, все не так просто.
Например, в следующей демонстрации мы включаем несколько флажков, чтобы позволить пользователю выбирать свои интересы (см. Полную версию в разделе « Examples »).
<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
. Когда эти данные достигают серверной стороны, вы должны уметь отображать их как массив связанных значений и относиться к ним соответствующим образом — см., Например, « Управление несколькими флажками с помощью Single Serverside Variable» .
По умолчанию установлены флажки
Чтобы установить флажок по умолчанию, вы просто присвойте ему атрибут checked
. См. Пример ниже:
<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>
Предоставление большей площади для ваших флажков
В приведенных выше примерах вы, возможно, заметили, что вы можете переключать флажок, нажимая на свой связанный элемент <label>
а также на флажок. Это действительно полезная функция меток HTML-форм, которая упрощает выбор нужного вам параметра, особенно на устройствах с малым экраном, таких как смартфоны.
Помимо доступности, это еще одна веская причина правильно настроить элементы <label>
в ваших формах.
Флажки неопределенного состояния
В дополнение к проверенным и непроверенным состояниям есть третье состояние, в которое может быть установлен флажок: неопределенный . Это состояние, в котором невозможно сказать, включен или выключен элемент. Это задается с помощью indeterminate
свойства объекта HTMLInputElement
с помощью JavaScript (его нельзя установить с помощью атрибута HTML):
inputInstance.indeterminate = true;
Флажок в неопределенном состоянии имеет горизонтальную линию в поле (он выглядит как знак дефиса или минуса) вместо проверки / отметки в большинстве браузеров.
Для этого свойства не так много вариантов использования. Наиболее распространенным является наличие флажка, который «владеет» несколькими дополнительными опциями (которые также являются флажками). Если все вспомогательные параметры отмечены, флажок владельца также проверяется, и если все они не отмечены, флажок владельца не установлен. Если какой-либо один или несколько подпараметров имеют другое состояние, чем другие, флажок владельца находится в неопределенном состоянии.
Это можно увидеть в приведенном ниже примере (благодаря CSS-трюкам для вдохновения). В этом примере мы отслеживаем ингредиенты, которые мы собираем для рецепта. Когда вы установите флажок или снимите флажок с ингредиента, функция JavaScript проверяет общее количество проверенных ингредиентов:
- Если ни один из них не установлен, флажок «Название рецепта» установлен на непроверенный.
- Если один или два отмечены, флажок «Название рецепта» установлен в
indeterminate
. - Если все три отмечены, флажок «Название рецепта» установлен на
checked
.
Таким образом, в этом случае indeterminate
состояние используется, чтобы заявить, что сбор ингредиентов начался, но рецепт еще не завершен.
var overall = document.querySelector('input[id="EnchTbl"]'); var ingredients = document.querySelectorAll('ul input'); overall.addEventListener('click', function(e) { e.preventDefault(); }); for(var i = 0; i < ingredients.length; i++) { ingredients[i].addEventListener('click', updateDisplay); } function updateDisplay() { var checkedCount = 1; for(var i = 0; i < ingredients.length; i++) { if(ingredients[i].checked) { checkedCount++; } } if(checkedCount === ingredients.length + 1) { overall.checked = true; overall.indeterminate = false; } else if(checkedCount <= ingredients.length + 1 && checkedCount > 1) { overall.checked = false; overall.indeterminate = true; } else { overall.checked = false; overall.indeterminate = false; } }
Проверка
Флажки действительно поддерживают validation (предлагаются для всех <input>
s). Однако большинство значений ValidityState
s всегда будут false
. Если флажок имеет required
атрибут, но не установлен, то значение ValidityState.valueMissing
будет true
.
Примеры
Следующий пример представляет собой расширенную версию примера «множественных флажков», который мы видели выше, — он имеет больше стандартных опций, а также «другой» флажок, который при проверке приводит к появлению текстового поля для ввода значения для «другой» опции. Это достигается с помощью простого блока JavaScript. Пример также включает некоторые CSS для улучшения стиля.
HTML
<form> <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> <div> <input type="checkbox" id="art" name="interest" value="art"> <label for="art">Art</label> </div> <div> <input type="checkbox" id="sports" name="interest" value="sports"> <label for="sports">Sports</label> </div> <div> <input type="checkbox" id="cooking" name="interest" value="cooking"> <label for="cooking">Cooking</label> </div> <div> <input type="checkbox" id="other" name="interest" value="other"> <label for="other">Other</label> <input type="text" id="otherValue" name="other"> </div> <div> <button type="submit">Submit form</button> </div> </fieldset> </form>
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
var otherCheckbox = document.querySelector('input[value="other"]'); var otherText = document.querySelector('input[id="otherValue"]'); otherText.style.visibility = 'hidden'; otherCheckbox.onchange = function() { if(otherCheckbox.checked) { otherText.style.visibility = 'visible'; otherText.value = ''; } else { otherText.style.visibility = 'hidden'; } };
Совместимость с браузером
Мы конвертируем наши данные совместимости в машиночитаемый формат JSON . Эта таблица совместимости по-прежнему использует старый формат, потому что мы еще не преобразовали содержащиеся в нем данные. Узнайте, как вы можете помочь!
code-examples.net