Как сделать checkbox активным

от admin

<input type="checkbox">

<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 — 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 controls exist, radio buttons allow one to be selected out of them all, whereas checkboxes allow multiple values to be selected.

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:

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 .

Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked ); the value is not submitted to the server at all. If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type=»hidden»> inside the form with the same name and value , generated by JavaScript perhaps.

Additional attributes

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

A Boolean attribute indicating whether this checkbox is checked by default (when the page loads). It does not indicate whether this checkbox is currently checked: if the checkbox’s state is changed, this content attribute does not reflect the change. (Only the HTMLInputElement ‘s checked IDL attribute is updated.)

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. 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.

The value attribute is one which all <input> s 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).

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

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

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):

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.

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

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.

Input Checkbox checked by default

For the life of me I cant set my CheckBox to checked at page load. I have tried adding value=»true» and Checked=»checked» after id and still nothing. Any ideas?

6 Answers 6

just write «checked» and it works

Orange Orange's user avatar

added «true» parameter below, just try it before, and it works for me

Peter ID's user avatar

The attribute checked=»checked» does work and the shorthand notation is just checked .

I tried all above solutions and nothing worked. It did give me some terminology to continue my research. What I ended up doing was going to the bottom of the code and added $(‘#inline’).prop(‘checked’, true); This solved my problem.

Читать:
Почему не работает лейзи медиа делюкс

Igorski88's user avatar

You’re looking for the checked content attribute. Here’s the relevant snippet from the official documentation: (Living Standard):

The checked content attribute is a boolean attribute that gives the default checkedness of the input element. When the checked content attribute is added, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to true; when the checked content attribute is removed, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to false.

Note the docs have links to definition of relevant terms.

If it seems too technical, you can always go to MDN page on checked . MDN contributors have put up considerable effort into «translating» HTML Standard into more readable/understandable form (often times with examples), especially useful to people without a solid foundation on web related terminology and concepts.

Note: You’ll also find the direct answer to your question on MDN.

<input type=»checkbox»>

<input> Элементы <input> типа checkbox по умолчанию отображаются как поля, которые отмечены (отмечены) при активации, как вы могли видеть в официальной правительственной бумажной форме. Точный вид зависит от конфигурации операционной системы, в которой работает браузер. Обычно это квадрат, но у него могут быть закругленные углы. Флажок позволяет вам выбрать отдельные значения для отправки в форму (или нет).

Try it

Примечание. Радиокнопки похожи на флажки, но с важным отличием: радиокнопки сгруппированы в набор, в котором одновременно может быть выбрана только одна радиокнопка, тогда как флажки позволяют включать и выключать отдельные значения. Там, где существует несколько элементов управления, переключатели позволяют выбрать один из них, а флажки позволяют выбрать несколько значений.

Value

Строка, представляющая значение флажка. Это не отображается на стороне клиента, но на сервере это value , присвоенное данным, отправленным с name флажка . Возьмем следующий пример:

В этом примере у нас есть имя subscribe и значение newsletter . Когда форма отправлена, пара данных имя / значение будет subscribe=newsletter .

Если value атрибута было опущено, значение по умолчанию для этого маркера on , так что представленные данные в этом случае будут subscribe=on .

Примечание. Если флажок не установлен при отправке формы, на сервер не отправляется значение, представляющее его непроверенное состояние (например, value=unchecked ); значение вообще не отправляется на сервер. Если вы хотите отправить значение по умолчанию для флажка, когда он не отмечен, вы можете включить <input type = «hidden»> внутри формы с тем же name и value , возможно, сгенерированным JavaScript.

Additional attributes

В дополнение к общим атрибутам, общим для всех элементов <input> , входы « checkbox » поддерживают следующие атрибуты.

Логический атрибут, указывающий, установлен ли этот флажок по умолчанию (при загрузке страницы). Он не указывает, установлен ли этот флажок в настоящее время: если состояние флажка изменилось, этот атрибут содержимого не отражает изменения. (Обновляется только checked IDL-атрибут HTMLInputElement HTMLInputElement

Примечание: В отличие от других элементов управления ввода, значение флажка в включаются только в представленных данных , если флажок в настоящее время checked . Если это так, то value атрибута значения флажка сообщается как входное значение. В отличии от других браузеров, Firefox по умолчанию сохраняется динамическое состояние проверяется из <input> по загрузке страницы. Используйте атрибут autocomplete для управления этой функцией.

value атрибута является тот , который все <input> Отправить; однако он служит специальной цели для входных данных типа checkbox : при отправке формы на сервер отправляются только те флажки, которые в данный момент отмечены, а сообщаемое значение является value атрибута value . Если value не указано иное, то строка on умолчанию. Это показано в разделе « Значение» выше.

Использование флажковых входов

Мы уже рассказали о наиболее основном использовании флажков выше.Теперь давайте посмотрим на другие общие функции и техники,связанные с флажками,которые вам понадобятся.

Обработка нескольких флажков

Пример,который мы видели выше,содержал только один флажок;в реальных ситуациях вы,скорее всего,столкнетесь с несколькими флажками.Если они полностью не связаны,то вы можете просто работать с ними по отдельности,как показано выше.Однако,если они все связаны,то все не так просто.

Например, в следующей демонстрации мы включаем несколько флажков, чтобы позволить пользователю выбирать свои интересы (см. Полную версию в разделе « Примеры »).

В этом примере вы увидите, что мы дали каждому флажку одно и то же name . Если оба флажка отмечены, а затем форма отправлена, вы получите строку пар имя/значение, представленную следующим образом: interest=coding&interest=music . Когда эта строка достигает сервера, вам нужно проанализировать ее иначе, чем как ассоциативный массив, чтобы были захвачены все interest Об одном методе, используемом с Python, см ., например, в разделе Обработка нескольких флажков с помощью одной переменной на стороне сервера .

Флажки по умолчанию

Чтобы установить флажок по умолчанию, вы присваиваете ему атрибут checked . См. Пример ниже:

Обеспечивая большую область попадания для ваших флажков

В приведенных выше примерах вы, возможно, заметили, что вы можете переключить флажок, щелкнув соответствующий элемент <label> , а также сам флажок. Это действительно полезная функция меток HTML-форм, которая упрощает выбор нужного параметра, особенно на устройствах с маленьким экраном, таких как смартфоны.

Помимо доступности, это еще одна веская причина для правильной настройки элементов <label> в ваших формах.

Флажки «Определить состояние

Помимо отмеченных и снятых отметок, есть третье состояние, в котором может находиться флажок: неопределенный . Это состояние, в котором невозможно сказать, включен или выключен элемент. Это устанавливается с помощью HTMLInputElement объекта indeterminate свойства с помощью JavaScript (он не может быть установлен с помощью атрибута HTML):

Флажок в неопределенном состоянии имеет горизонтальную линию в окошке (это выглядит как дефис или знак минуса)вместо флажка/галочки в большинстве браузеров.

Для этой недвижимости не так уж и много случаев использования.Наиболее распространенным является ситуация,когда доступен флажок,который «владеет» рядом вложенных опций (которые также являются флажками).Если все вложенные опции отмечены,флажок «владеет» также отмечен,и если они все сняты,флажок «владеет» не отмечен.Если одна или более вложенных опций имеют другое состояние,чем другие,флажок обладание находится в неопределенном состоянии.

Это можно увидеть в приведенном ниже примере (спасибо CSS Tricks за вдохновение). В этом примере мы отслеживаем ингредиенты, которые собираем для рецепта. Когда вы устанавливаете или снимаете флажок ингредиента, функция JavaScript проверяет общее количество проверенных ингредиентов:

  • Если ни один из пунктов не отмечен,флажок с именем рецепта будет снят.
  • Если один или два отмечены, флажок названия рецепта устанавливается на indeterminate .
  • Если все три проверяется, флажок имени рецепта установлен в положении checked .

Таким образом, в этом случае indeterminate состояние используется для обозначения того, что сбор ингредиентов начался, но рецепт еще не завершен.

Примечание. Если вы отправляете форму с неопределенным флажком, происходит то же самое, как если бы флажок был снят — никакие данные не отправляются для представления флажка.

Validation

Флажки поддерживают проверку (предлагается всем <input> ). Однако большинство ValidityState всегда будет false . Если флажок имеет required атрибут, но не установлен, то ValidityState.valueMissing будет true .

Examples

Следующий пример является расширенной версией примера «нескольких флажков»,который мы рассматривали выше-в нем больше стандартных опций,плюс флажок «другой»,который при установке флажка вызывает появление текстового поля для ввода значения опции «другой».Это достигается с помощью простого блока JavaScript.Пример также включает некоторые CSS для улучшения стиля.

Флажок checkbox

Флажок checkbox представляет собой элемент (галочку или птичку) HTML формы, который может иметь два состояния: отмечен и не отмечен.

Флажок создается с помощью тега input с атрибутом type в значении checkbox . Внешний вид флажка:

Отмеченный чекбокс будет посылать на сервер содержимое атрибута value . Если атрибута value у чекбокса нет — он будет посылать строку «on». Если чекбокс не отмечен — ничего не будет присылаться на сервер не зависимо от наличия атрибута value .

Пример

Давайте сделаем два флажка checkbox: пусть первый будет отмечен (так как ему дан атрибут checked ), а второй — нет:

Пример . Заблокированный чекбокс

Давайте посмотрим на заблокированный с помощью атрибута disabled флажок. При нажатии на него его состояние не будет меняться:

Пример . Заблокированный и отмеченный чекбокс

А теперь давайте заблокируем флажок, в отмеченном состоянии, атрибутом disabled и зададим ему атрибут checked :

Похожие статьи