sonyps4.ru

Checkbox html значение по умолчанию. Стилизация чекбоксов и радиокнопок на чистом CSS с совместимостью для старых браузеров

Это руководство познакомит вас с флажками (checkbox) HTML и научит обращаться с ними в PHP .

Форма из одного флажка

Давайте создадим простою форму с одним флажком (checkbox).

Вам нужен доступ в интернет?

В PHP скрипте (файл checkbox-form.php) возможно прочитать значение поля посредством массива $_POST . Если $_POST["formWheelchair"] присвоено значение YES, то флажок в был выбран. Если флажок не выбран, то переменная $_POST["formWheelchair"] не установлена.

Вот пример обработки формы на PHP:

Переменной $_POST["formWheelchair"] присвоено значение YES, так как значение атрибута value тега input равно «YES» .

Атрибуту value вместо YES можно установить 1. Не забудьте ваш обновить ваш PHP код, соответственно установленным значениям.

Группа флажков

Нередко возникают ситуации, когда в форму необходимо вставить несколько флажков. Особенно в том случае, когда пользователю необходимо предоставить право выбора из нескольких вариантов. Это важно, так как, например, переключатель (radio) можно выбрать всего один.

Давайте составим форму, которая предоставит пользователю несколько вариантов выбора.

Выберите здания, которые необходимо посетить.
Acorn Building
Brown Hall
Carnegie Complex
Drake Commons
Elliot House

Пожалуйста отметьте, что все флажки имеют одно имя (formDoor). Одно имя говорит о том, что все флажки связаны между собой. Квадратные скобки указывают на то, что все значения будут доступны из одного массива. То есть $_POST["formDoor"] не вернет строку, как в примере выше, вместо нее возвратится массив, содержащий значения флажков, которые были выбраны пользователем.

Например, если я отмечу все флажки, $_POST["formDoor"] вернет массив из {A,B,C,D,E} . В примере ниже мы получаем и отображаем все значения массива.

Функция empty пригодится на тот случай, если пользователь ничего не выбрал. Если же массив не пустой, подсчитываем количество выбранных флажков при помощи функции count и выводим все значения при помощи цикла for .

Если выбран флажок "Acorn Building", то массив будет содержать значение "A".

Проверяем, выбран ли конкретный флажок

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

Function IsChecked($chkname,$value) { if(!empty($_POST[$chkname])) { foreach($_POST[$chkname] as $chkval) { if($chkval == $value) { return true; } } } return false; }

Теперь достаточно просто вызвать функцию IsChecked (chkboxname,значение). Например:

If(IsChecked("formDoor","A")) { //do ... }

Note: Unlike other input controls, a checkboxes 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.

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

Choose your interests

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:

Choose your interests

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 element represents a caption for an item in a user interface.">

Beyond accessibility, this is another good reason to properly set up

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

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

Choose your interests

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"); var otherText = document.querySelector("input"); 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 "" in that specification.
Living Standard
HTML5
The definition of "" in that specification.
Recommendation

Browser compatibility

The compatibility table on this page is generated from structured data. If you"d like to contribute to the data, please check out

Opera for Android Safari on iOS Samsung Internet type="checkbox" Chrome Full support Yes Edge Full support Yes Firefox Full support Yes IE Full support Yes Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Edge Mobile Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android ?

Legend

Full support Full support Compatibility unknown Compatibility unknown

See also

  • element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent."> and the elements."> HTMLInputElement interface which implements it.
  • The ), checkbox (), or option (
Загрузка...