Как получить данные из кнопки checkbox input пример

All attributes of input

Attribute name Values Notes
step Specifies the interval between valid values in a number-based input.
required Specifies that the input field is required; disallows form submission and alerts the user if the required field is empty.
readonly Disallows the user from editing the value of the input.
placeholder Specifies placeholder text in a text-based input.
pattern Specifies a regular expression against which to validate the value of the input.
multiple Allows the user to enter multiple values into a file upload or email input.
min Specifies a minimum value for number and date input fields.
max Specifies a maximum value for number and date input fields.
list Specifies the id of a <datalist> element which provides a list of autocomplete suggestions for the input field.
height Specifies the height of an image input.
formtarget Specifies the browsing context in which to open the response from the server after form submission. For use only on input types of «submit» or «image».
formmethod Specifies the HTTP method (GET or POST) to be used when the form data is submitted to the server. Only for use on input types of «submit» or «image».
formenctype Specifies how form data should be submitted to the server. Only for use on input types «submit» and «image».
formaction Specifies the URL for form submission. Can only be used for type=»submit» and type=»image».
form Specifies a form to which the input field belongs.
autofocus Specifies that the input field should be in focus immediately upon page load.
accesskey Defines a keyboard shortcut for the element.
autocomplete Specifies whether the browser should attempt to automatically complete the input based on user inputs to similar fields.
border Was used to specify a border on an input. Deprecated. Use CSS instead.
checked Specifies whether a checkbox or radio button form input should be checked by default.
disabled Disables the input field.
maxlength Specifies the maximum number of characters that can be entered in a text-type input.
language Was used to indicate the scripting language used for events triggered by the input.
name Specifies the name of an input element. The name and value of each input element are included in the HTTP request when the form is submitted.
size Specifies the width of the input in characters.
src Defines the source URL for an image input.
type buttoncheckboxfilehiddenimagepasswordradioresetsubmittext Defines the input type.
value Defines an initial value or default selection for an input field.

How To Create a Custom Radio Button

Example

/* Customize the label (the container) */.container {  display: block; 
position: relative;  padding-left: 35px;  margin-bottom:
12px;  cursor: pointer;  font-size: 22px;  -webkit-user-select:
none;  -moz-user-select: none;  -ms-user-select: none; 
user-select: none;}/* Hide the
browser’s default radio button */.container input {  position: absolute; 
opacity: 0;  cursor: pointer;  height: 0;  width:
0;
}/* Create a custom radio button */.checkmark {  position:
absolute;  top: 0;  left: 0;  height: 25px; 
width: 25px;  background-color: #eee;  border-radius: 50%;
}/* On mouse-over, add a grey background color
*/.container:hover input ~ .checkmark {  background-color: #ccc;
}/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {  background-color: #2196F3;
}/* Create the indicator (the dot/circle — hidden when not checked) */.checkmark:after
{  content: «»;  position: absolute;  display:
none;}/* Show
the indicator (dot/circle) when checked */.container input:checked ~ .checkmark:after
{  display: block;}/* Style the indicator (dot/circle) */
.container .checkmark:after {  top: 9px;  left: 9px; 
width: 8px;  height: 8px;  border-radius: 50%; 
background: white;}

❮ Previous
Next ❯

How To Create a Custom Checkbox

Step 1) Add HTML:

<label class=»container»>One  <input type=»checkbox»
checked=»checked»>  <span class=»checkmark»></span></label><label class=»container»>Two  <input type=»checkbox»> 
<span class=»checkmark»></span></label>
<label class=»container»>Three  <input type=»checkbox»> 
<span class=»checkmark»></span></label><label class=»container»>Four 
<input type=»checkbox»>  <span class=»checkmark»></span></label>

Step 2) Add CSS:

/* Customize the label (the container) */.container {  display: block; 
position: relative;  padding-left: 35px;  margin-bottom:
12px;  cursor: pointer;  font-size: 22px;  -webkit-user-select:
none;  -moz-user-select: none;  -ms-user-select: none; 
user-select: none;}/* Hide the
browser’s default checkbox */.container input {  position: absolute; 
opacity: 0;  cursor: pointer;  height: 0;  width:
0;
}/* Create a custom checkbox */.checkmark {  position:
absolute;  top: 0;  left: 0;  height: 25px; 
width: 25px;  background-color: #eee;}/* On mouse-over, add a grey background color */.container:hover
input ~ .checkmark {  background-color: #ccc;}/* When the
checkbox is checked, add a blue background */.container input:checked ~
.checkmark {  background-color: #2196F3;}/* Create the
checkmark/indicator (hidden when not checked) */.checkmark:after { 
content: «»;  position: absolute;  display: none;}/* Show the
checkmark when checked */.container input:checked ~ .checkmark:after { 
display: block;}/* Style the checkmark/indicator */.container
.checkmark:after {  left: 9px;  top: 5px;  width:
5px;  height: 10px;  border: solid white; 
border-width: 0 3px 3px 0;  -webkit-transform: rotate(45deg); 
-ms-transform: rotate(45deg);  transform: rotate(45deg);}

HTML CheckBox Example

A simple example, many places you saw this form to fill your detail. Example registration form of .

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>Check Box</h2>

<p> HTML checkbox examples : Select your gender</p>
<input type=»checkbox» name=»genderM» value=»Male»> Male <br>
<input type=»checkbox» name=»genderF» value=»Female»> Female<br>

</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14

<!DOCTYPE html>

<html>

<head>

<head>

<body>

<h2>Check Box<h2>

<p>HTML checkbox examplesSelect your gender<p>

<input type=»checkbox»name=»genderM»value=»Male»>Male<br>

<input type=»checkbox»name=»genderF»value=»Female»>Female<br>

<body>

<html>

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:

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.

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

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

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

Объект переключатель в javascript — radio и свойство checked

Элемент javascript предназначен для выбора только одного единственного варианта из нескольких.

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

Рассмотрим пример использования радиокнопок:
html-код:

<body>
<form name="f1">
Ваш пол:<br>
<input type="radio" name="r1" id="id1">м<br>
<input type="radio" name="r1" id="id2">ж<br>
<input type="button" onclick="fanc()">
<form>
<body>

Группа радиокнопок (radio) идентифицируется в скрипте следующим образом:
Скрипт:

function fanc(){
  document.getElementById("id1").checked=true;    
  document.f1.r1.checked=true;
  document.f1'r1'.checked=true;		
}

Первый способ является наиболее предпочтительным.

Рассмотрим пример использования в javascript с свойством:

Пример: По щелчку на кнопке устанавливать первый переключатель отмеченным

Скрипт:

function fanc(){
	document.f1.r1.checked=true;
}

HTML-код:

<form name="f1">
<input type="radio"   name="r1">пункт1<br>
<input type="radio"   name="r1">пункт1<br>
<input type="button" onClick ="fanc()" value="отметить">
<form>

Задание js12_2.
Создать страницу проверки знаний учащегося с вопросом: «Какой заряд у электрона?» и двумя ответами: «положительный» (неправильный) и «отрицательный» (правильный). Осуществить проверку правильности отмеченного при помощи элемента формы ответа. Функцию проверки запускать

Вариант №1 проверки чокнутого checkbox

Нам потребуется тег input с уникальным идентификатором(id) и еще кнопка по которой мы будем нажимать!

<input type=»checkbox» id=»rules»><i>Я согласен с <a href=»ссылка»>Условиями</a></i>
<button id=»submit»>Создать аккаунт</button>

Далее нам понадобится скрипт, который сможет определить, msk kb накат чекбокс или нет:

if (rules.checked) { alert(«Чекбокс нажат -вариант №1»); } else { alert(«Чекбокс не нажат-вариант №1»); }

Теперь нам понадобится onclick, для отслеживания нажатия на кнопку! И соберем весь код вместе:

<input type=»checkbox» id=»rules»><i>Я согласен с <a href=»https://dwweb.ru/page/more/rules.html» target=»_blank»>Условиями</a></i>

<button id=»submit»>Создать аккаунт</button>

<script>

submit.onclick = function(){

if (rules.checked) { alert(«Чекбокс нажат -вариант №1»); } else { alert(«Чекбокс не нажат-вариант №1»); }

}

</script>

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:

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.

Get The value from CheckBox

Getting the value of Checkbox either it’s checked or not. You have to define it in a form tag then input with a value of it. See the below example How to get the HTML CheckBox checked value and HTML CheckBox value if not checked.

In the example we are using a button type ( to perfomat action), javascript and if condition statement. If Checkbox is checked the only value of it show in the alert box.

<!DOCTYPE html>
<html>
<body>

<h2>Get Checkbox value</h2>

<input type=»checkbox» id=»m» value=»male»> Male

<button onclick=»display()»>Display Value</button>
<script>
function display() {
if (document.getElementById(«m»).checked){
var x = document.getElementById(«m»).value;
}
alert(«The value of the checkbox is: » + x);
}
</script>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

<!DOCTYPE html>

<html>

<body>

<h2>Get Checkbox value<h2>

<input type=»checkbox»id=»m»value=»male»>Male

<button onclick=»display()»>DisplayValue<button>

<script>

functiondisplay(){

if(document.getElementById(«m»).checked){

varx=document.getElementById(«m»).value;

}

alert(«The value of the checkbox is: «+x);

}

</script>

<body>

<html>

Output: In A GIF

2). Получение значения нескольких checkbox

Второй способ банальный, каждому checkbox присвоить уникальное имя(name)и каждый чекбокс обрабатывать индивидуально!

Я тут думал о самом простом примере получения value из кнопки checkbox Input!

В чем главная проблема!? В том, что нам нужно:

1). сделать какое то действие onclick, 2). потом определить тег(любой id — в смысле уникальный якорь(образно.))3). и только уже после этого получить значение из value type checkbox Input4). И первый вариант — это когда кнопка радио 0- одиночная кнопка:

В нашей кнопке в данном случае, обязательное условие id — мы как-то должны обратиться к тегу

<input type=»checkbox» id=»my_id» value=»my_id_value»>Чекбокс пример получения value<br>
Ну и далее повесим на наш id onclick и внутри выведем содержание value чекбокса alert( my_id.value );

<script>

my_id.onclick = function(){

alert( my_id.value );

};

</script>

Вы можете проверить работоспособность данного получения значения value из type checkbox Input в js

Чекбокс пример получения value

Получение значений из нескольких чекбоксов инпута в js также просто, как и в php!

Для иллюстрации сбора чекбоксов нам потребуются эти чекбоксы и кнопка в виде ссылки с id:

<input type=»checkbox» value=»red» name=»co»>Красный

<input type=»checkbox» value=»green» name=»co»>Зеленый

<input type=»checkbox» value=»blue» name=»co»>Синий

<a id=»to_send»>отправить</a>

Скрипт, который соберет вся нажатые чекбоксы(checked)! Обращаю ваще внимание, что внутри скрипта checkbox — это не тип… checkbox — это переменная(массив)(почему такое возможно!? Всё просто : type=checkbox — это из html, а var checkbox из js), они из разных сред. После проверки, если чекбокс был отмечен, заносим данные в переменную(str) с пробелом, далее выводим результат через alert

После проверки, если чекбокс был отмечен, заносим данные в переменную(str) с пробелом, далее выводим результат через alert

<script>

window.onload = function() {

var checkbox;

to_send. onclick = function()

{

  checkbox = document.getElementsByName(«co»);

  var str = «»;

  for(var i=0; i<checkbox.length; i++){

  if(checkbox . checked) {str+=checkbox.value+» «;}

  }

  alert(str);

}

}

</script>

Для того, чтобы получить сразу несколько позиций checkbox — нажмите кнопку отправить!

Красный Зеленый Синий отправить

Для того, чтобы получить значение value в переменную в php? то вам нужно в результата вывода поменять echo на любую переменную и уже там делать все, что вам захочется…

if( $_POST ) { $здесь_переменная = strip_tags($_POST);}

Атрибут value

Атрибут value — это строка DOM , содержащая значение радиокнопки. Это значение никогда не показывается пользователю его веб-браузером. Атрибут value используется для того, чтобы точно определить какая из радиокнопок была выбрана пользователем.

Создание группы радиокнопок

Группа радиокнопок определяется путём присвоения каждой радиокнопке в данной группе одного и того же значения атрибута ( name ). Выбор любой радиокнопки в этой группе автоматически отменяет выбор другой радиокнопки в той же группе.

Вы можете создать любое количество групп радиокнопок, если каждой из этих групп будет присвоено своё уникальное значение атрибута name .

HTML будет выглядеть следующим образом:

Здесь Вы видите три радиокнопки, каждая из которых имеет атрибут name со значением «contact» и уникальный атрибут value , который однозначно идентифицирует эту радиокнопку в данной группе. Каждой радиокнопке присвоен уникальный id , связанный с тегом представляет собой подпись к элементу пользовательского интерфейса.»> через атрибут for для установления связи между конкретной меткой и конкретной радиокнопкой.

Вы можете опробовать этот код здесь:

Представление данных группы радиокнопок

Когда представленная выше форма отправляется на сервер с информацией о выбранной радиокнопке, то её данные включают запись в виде «contact=name». Например, если пользователь кликает на радиокнопку «Phone», а затем отправляет форму на сервер, данные формы будут включать в себя строку «contact=phone» .

Если Вы пренебрежёте атрибутом value в Вашем HTML, то отправленные данные просто присвоят данной группе значение «on» . То есть, если пользователь кликнет на радиокнопку «Phone» и отправит форму, итоговые данные отобразятся как «contact=on» и будут абсолютно бесполезны. Поэтому никогда не забывайте указывать атрибут value !

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

Поскольку отправлять пустую форму в большинстве случаев не имеет никакого смысла, то разумно оставлять одну радиокнопку активированной по умолчанию с помощью атрибута «checked» . Смотрите здесь Selecting a radio button by default.

Давайте добавим немного кода в наш пример для того, чтобы изучить данные, полученные из этой формы. HTML изменяется путём добавления блока

Затем добавим немного JavaScript. Установим слушателя для события submit , которая будет отправляться при клике пользователя на кнопку «Отправить»:

Опробуйте этот пример и убедитесь, что для группы радиокнопок «contact» будет только один результат.

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.

This article has been fully translated into the following languages:

  • German

  • Portuguese

  • Russian

  • Thai

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

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

Check all the languages you have proficiency in.

HTML CSS JS PHP Ruby INTERCAL

The natural way to represent this in you application code (server-side or front-end) is with an array.

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.

I agree to all terms and conditions.

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 attribute, or you can give each one a different .

If you use the same for all, your request string will look like this: If you use different names, it looks like this: The first one seems a bit preferable, but what happens when you get to PHP and try to get the values?

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.

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

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Одиночный чекбокс

Создадим простую форму с одним чекбоксом:

<form action="checkbox-form.php" method="post">
    Do you need wheelchair access?
    <input type="checkbox" name="formWheelchair" value="Yes" />
    <input type="submit" name="formSubmit" value="Submit" />
</form>

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

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

<?php

if(isset($_POST) && 
   $_POST == 'Yes') 
{
    echo "Need wheelchair access.";
}
else
{
    echo "Do not Need wheelchair access.";
}

?>

Для $_POST было установлено значение “Yes”, так как это значение задано в атрибуте чекбокса value:

<input type="checkbox" name="formWheelchair" value="Yes" />

Вместо “Yes” вы можете установить значение «1» или «on«. Убедитесь, что код проверки в скрипте PHP также обновлен.

Группа че-боксов

Иногда нужно вывести в форме группу связанных PHP input type checkbox. Преимущество группы чекбоксов заключается в том, что пользователь может выбрать несколько вариантов. В отличие от радиокнопки, где из группы может быть выбран только один вариант.

Возьмем приведенный выше пример и на его основе предоставим пользователю список зданий:

<form action="checkbox-form.php" method="post">

Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House

<input type="submit" name="formSubmit" value="Submit" />

</form>

Обратите внимание, что input type checkbox имеют одно и то же имя (formDoor[]). И что каждое имя оканчивается на []

Используя одно имя, мы указываем на то, что чекбоксы связаны. С помощью [] мы указываем, что выбранные значения будут доступны для PHP скрипта в виде массива. То есть, $_POST возвращает не одну строку, как в приведенном выше примере; вместо этого возвращается массив, состоящий из всех значений чекбоксов, которые были выбраны.

Например, если я выбрал все варианты, $_POST будет представлять собой массив, состоящий из: {A, B, C, D, E}. Ниже приводится пример, как вывести значение массива:

<?php
  $aDoor = $_POST;
  if(empty($aDoor)) 
  {
    echo("Вы не выбрали ни одного здания.");
  } 
  else
  {
    $N = count($aDoor);

    echo("Вы выбрали $N здание(й): ");
    for($i=0; $i < $N; $i++)
    {
      echo($aDoor . " ");
    }
  }
?>

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

Если флажок установлен для варианта «Acorn Building«, то массив будет содержать значение ‘A‘. Аналогично, если выбран «Carnegie Complex«, массив будет содержать C.

Проверка, выбран ли конкретный вариант

Часто требуется проверить, выбран ли какой-либо конкретный вариант из всех доступных элементов в группе HTML input type checkbox. Вот функция, которая осуществляет такую проверку:

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

Чтобы использовать ее, просто вызовите IsChecked (имя_чекбокса, значение). Например:

if(IsChecked('formDoor','A'))
{
//сделать что-то ...
}
//или использовать в расчете ...

$price += IsChecked('formDoor','A') ? 10 : 0;
$price += IsChecked('formDoor','B') ? 20 : 0;

Скачать пример кода

Скачать PHP код примера формы с PHP input type checkbox.

Данная публикация является переводом статьи «Handling checkbox in a PHP form processor» , подготовленная редакцией проекта.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector