Adding checkbox in html

How to create and use a HTML checkbox ?

The HTML checkbox form control can only have two checked states (via its checked attribute):

If you want to get always a value for a property (ie false or true), you can:

Base Demo

This demo shows that if the checkbox is checked, the property given by the name attribute (with value property-name ) will be added to the data send by the form with the default value of on

Syntax

The syntax of a checkbox is:

checked is the optional checked attribute (default to false ) that sets the state of the checkbox (How to change it programmatically)

Value

If a checkbox is unchecked when its form is submitted, the field data is just not sent.

There is no not-checked value

Default

The default value is on and never changes.

document.querySelector("input").addEventListener("click", function()< console.log(`The checkbox is checked ? $`); console.log(`The value is $`); >); 

If Set

If the value attribute is set, this value will be send instead

document.querySelector("form").addEventListener("submit", function(event)< event.preventDefault(); let formData = new FormData(this); let i = 0; for (let entry of formData) < i++; console.log(`Entry $`); console.log(entry); > console.log(`Number of field sent: $`); >); 

Visual / Styling

Css

Switch

 

Button

Keyboard Navigation

You may navigate with the tab key because a input (and alos checkbox) is by default focusable. You still may change the order of navigation via the tabindex value.

the third tab will get you on the next interactive element in the iframe (ie a link) — the code is rendered in a iframe

How to

How to change the state programmatically

The checked attribute of the input checkbox element permits:

function toggleCheckBox(event) < event.preventDefault(); if (event.target.checkbox.checked)< event.target.checkbox.checked = false; event.target.button.innerHTML= "Check the checkbox"; >else < event.target.checkbox.checked = true; event.target.button.innerHTML= "Uncheck the checkbox"; >> 

How to use a checkbox to enable or disable other Form elements

Example of a legend with a checkbox that controls whether or not the fieldset is enabled

 

Aria Role

With aria role, you need to handle programmatically the state of each attribute as seen in this example 3)

[role='checkbox'][aria-checked='false']:before < content: '\00a0\00a0'; width: 14px; height: 14px; border: 1px solid hsl(0, 0%, 66%); border-radius: 0.2em; background-image: linear-gradient(to bottom, hsl(300, 3%, 93%), #fff 30%); >[role='checkbox'][aria-checked='true']:before < content: url('/_media/web/html/checkbox_checked.png'); >[role='checkbox'].focus
 
Sandwich Condiments
Lettuce
Tomato
Mustard
Sprouts

Documentation / Reference

Formdata Browser Devtool

FormData is a web api object that represent the data of a form that should be send if the form is submited. Therefore if you have a checkbox that is not checked, formdata will not collect it. You can.

checked is an HTML attribute that indicates via its value (true or false — default to true) if the form control element is checked. It’s used: in a checkbox or radio button select optionselected.

control form elements are element that are used specifically inside a form. They are used: to specify a key and a value. to layout the form to submit or reset it field set [optional] that.

An inputinput element of a form control that permits to define a scalar value inputFull list Ref Doc The type attribute defined: the default behavior the design of the element. and the.

HTML The label html element represents a caption for a control item in a form (user interface). idfor A click on the label: will bring focus on the control element. propagates to the control.

legend is an element that represents a caption for the fieldset element. Example of a legend with a checkbox that controls whether or not the fieldset is enabled .

Html Radio Illustration

A radio represents a serie of mutually-exclusive choices in a form. It is an input element of type radio. A radio is round to distinguish from the square checkbox. As the checkbox, the state.

Html Checkbox Illustration

This page shows you how you can create a checkbox in React. This example is written in JSX and shows you a controlled component. The react forms components input accept a value attribute that is used.

Источник

Как сделать чекбокс на HTML/CSS

Как сделать чекбокс на HTML/CSS

Сегодня вы узнаете как сделать чекбокс на HTML и добавить ему CSS стилей для лучшей совместимости с дизайном сайта.

Демонстрация

Чекбокс на HTML

Создадим блок с четырьмя чекбоксами, первый будет отмечен – с галочкой. Каждый чекбокс будет заключен в тег label, внутри которого поле для ввода, текст и элемент span, который предстоит стилизовать.

Как сделать чекбокс на HTML/CSS.

Тег label служит контейнером для каждого чекбокса, для наглядности я временно задал красную рамку тегу label. Когда мало опыта, это хороший способ, увидеть границы любого тега, чтобы не действовать вслепую.

Как сделать чекбокс на HTML/CSS.

CSS для чекбокс

Строчный тег label, заменим на блочный (display: block), чтобы чекбоксы, встали друг под другом, user-select: none – запрещает пользователю выделять элемент.

.container display: block;
user-select: none;
>

Этот код прячет дефолтные браузерные стили для чекбокса. Мы делаем элемент полностью прозрачным за счет opacity, width и height с нулевым значением и на их месте, задаем кастомные стили для чекбокса.

.container input opacity: 0;
height: 0;
width: 0;
>

Создаем кастомные чекбоксы. Меняем размеры и цвет фона.

.checkmark height: 23px;
width: 22px;
background-color: #eec321;
>

При наведении курсора, делаем цвет фона немного темнее.

.container:hover input ~ .checkmark background-color: #ccc678;
>

Для отмеченного чекбокса, задаем другой цвет для фона.

.container input:checked ~ .checkmark background-color: #2196f3;
>

Прячем галочку для не отмеченных чекбоксов, применив псевдоэлемент after.

.checkmark:after content: «»;
position: absolute;
display: none;
>

Делаем видимой галочку, только для отмеченных чекбоксов.

.container input:checked ~ .checkmark:after display: block;
>

Рисуем и стилизуем галочку. Галочку мы рисуем на чистом CSS. Изобразим прямоугольник с белой рамкой, у двух сторон прямоугольника, рамки нет (нулевая ширина), получается прямоугольный угол, мы его поворачиваем на 45 градусов и получается галочка.

.container .checkmark:after left: 8px;
top: 6px;
width: 6px;
height: 11px;
border: solid #fff;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
>

Как сделать чекбокс на HTML/CSS.

Посмотреть код целиком можно на Codepen

Создано 19.11.2018 10:19:41

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Checkboxes

    Using checkboxes is a good option when you want to give your visitors the option to choose several items from a group of choices. In that regard, the checkbox works opposite of a radio button, which only allows you to select one item from a group of choices. In its most simple form, a checkbox is simply an input element with the type property set to checkbox, like this:

    However, as with all input elements, you need to define a name for it to be usable — without a name, the element won’t be identifiable when posting the form back to a server for processing. You also want to set a value — this will be the value sent to the server if the checkbox has been checked. Here’s an example:

    With this example, if the checkbox has been checked and the form is submitted to a server, the server will be able to read the form element «nameOfChoice» and its value will be 1.

    Checked or not checked?

    Notice how all the checkboxes so far have not been checked from the beginning — the user would have to interact with the checkbox to change its state from unchecked to checked. This might be what you want, but sometimes, you want the checkbox to be checked by default, either to suggest a choice to the user or because you are showing a checkbox with a value that corresponds to an existing setting, e.g. from a database. Fortunately, this is very simple — just add the checked attribute to the checkbox:

    In the old days of XHTML, where each attribute should always have a value, even the boolean attributes, it would look like this:

    Either way should work in all modern browsers, but the first way is shorter and more «HTML5-like».

    Multiple choices

    So far, all our checkboxes have been simple switches, e.g. for defining whether an option is on or off. Checkboxes are great for that, but as mentioned, they can also be used to allow the user a selection of possible options. Let me show you a neat example where this makes sense:

      

    What is Your Favorite Pet?
    Cats

    Dogs

    Birds



    Notice how we now have multiple checkboxes, but they all share the same name («favorite_pet») but different values (e.g. «Dogs»). When this form is submitted back to the server, all these checkboxes will be represented by a single name, but the value will be an array of 0-3 items. If you had used radio buttons instead of checkboxes, the user would only be allowed to pick a single favorite animal, but with checkboxes, they can select none of them, all of them or some of them.

    Labels for checkboxes

    If you tested the previous example, you will notice that we can put text next to a checkbox, but they are still two separate things — you can’t click the text to trigger the checkbox. This can be really annoying for the user, but fortunately for us, it’s easy to solve: Just use the label element! Here’s a basic example to show you the difference:

    Two checkboxes — one without a label and one with. They might look almost identical, but the one with the label can be triggered by clicking both the actual checkbox and the attached label. This is nice if you’re sitting on a desktop PC with a mouse, but even better when you’re using a touch device like a smartphone, where small checkboxes can be hard to hit with your finger.

    The label is very simple — it uses the for attribute to attach itself to a form element with a matching id attribute (notice how I have «dogs» in both places).

    Working dynamically with a checkbox

    Just like any other DOM element, you are able to manipulate a checkbox using JavaScript. In that regard, it could be interesting to check whether a checkbox is checked or not and perhaps add some logic to control how many options a user can select. To show you how this can be done, I have extended a previous example (the «Favorite Pet» selector) to include some JavaScript magic:

      

    What is Your Favorite Pet?
    Cats

    Dogs

    Birds






    function ValidatePetSelection()
    <
    var checkboxes = document.getElementsByName("favorite_pet");
    var numberOfCheckedItems = 0;
    for(var i = 0; i < checkboxes.length; i++)
    <
    if(checkboxes[i].checked)
    numberOfCheckedItems++;
    >
    if(numberOfCheckedItems > 2)
    <
    alert("You can't select more than two favorite pets!");
    return false;
    >
    >

    Allow me to quickly run through what this code does. We have the same form as before, but we have added an event handler to each of the checkboxes, which causes them to call a JavaScript function (ValidatePetSelection) when the user clicks them. In this function, we get a hold of all the relevant checkboxes using the getElementsByName function and then we loop through them to see if they are checked or not — for each checked item, we add to a number. This number is then checked and if it exceeds two, then we alert the user about the problem (only two pets can be selected) and then we return false. Returning false will prevent the checkbox from being checked.

    This was just a simple example of how to work with checkboxes using JavaScript. You can do much more, especially if you use a JavaScript framework like jQuery, which will make it a lot easier to select and manipulate DOM elements.

    Summary

    Checkboxes allow you to setup selectable options for your users — either to toggle a single setting on or off, or to allow for multiple choices, like in the Favorite Pet example. You should use labels to tie your checkbox and the descriptive text together, to allow the user to click a larger area when manipulating the checkbox — this is also good for assisting technologies like screen readers for visually impaired.

    Is your preferred language not on the list? Click here to help us translate this article into your language!

    Источник

    Читайте также:  Php date format время
    Оцените статью