How to check if a checkbox is checked with PHP?

20

How to check if a checkbox is checked, in a form submit?

    
asked by Leandro Costa 13.02.2014 в 17:37
source

8 answers

26

If your HTML page looks like this:

<input type="checkbox" name="meucheckbox" value="umvalorqualquer">

When sent, if the check box is not checked, the meucheckbox variable will not exist, its value is NULL . If it is checked it receives the meucheckbox variable and its value will be onevalue .

On the PHP page, you can check the following form if the form is submitted via POST:

if(isset($_POST['meucheckbox']))
{
    echo "checkbox marcado! <br/>";
    echo "valor: " . $_POST['meucheckbox'];
}
else
{
    echo "checkbox não marcado! <br/>";
}

If the form is submitted via GET:

if(isset($_GET['meucheckbox']))
{
    echo "checkbox marcado! <br/>";
    echo "valor: " . $_GET['meucheckbox'];
}
else
{
    echo "checkbox não marcado! <br/>";
}


If the checkbox is checked, the result will be:

checkbox marcado!
valor: umvalorqualquer

If the checkbox is not checked, the result will be:

checkbox não marcado!
    
answered by 13.02.2014 / 18:28
source
8

A checkbox in an HTML form is only sent if it is checked, so just check if it is present in the variables $_GET or $_POST .

Example with method post :

isset($_POST['minhacheck'])

Example with method get :

isset($_GET['minhacheck'])

In this case, the HTML would be:

<input type="checkbox" name="minhacheck" value="valor">
    
answered by 13.02.2014 в 17:41
6
  //Aqui verifico se o post do checkbox me retorna um valor verdadeiro ou falso (true ou false)
  $checkbox = $_POST["CheckBox"] ? "Marcado (true)" : "Desmarcado (false)";
  echo $checkbox; // Imprimo a resposta.
    
answered by 17.02.2014 в 14:54
3

Working with checkbox with PHP is quite annoying because of this limitation the program receives the value only if it has been checked.

But this limitation only becomes noticeably annoying when you have many checkboxes on the same form, for example in a user access control permissions editor, where you would have to repeat dozens of times a ternary or create a loop check to simplify the process at the cost of winning cyclomatic complexity

Finally ... For these very specific cases you can modify the HTML by defining a field of type hidden of the same name as the checkbox:

<input type="hidden" name="meucheckbox" value="0" />
<input type="checkbox" name="meucheckbox" value="1" />

Given vertical processing, if the checkbox is not marked, you will still have, for example, a% value of 0 (zero) and, if checked, the entry will be replaced in the superglobal by the amount due.     

answered by 13.02.2014 в 20:02
3

The big balcony is in the form name the checkboxes as vector, as the example below:

<table border="0" width="100%">
<tr>
<td class="menu" width="130">
Treinamentos:
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="I"> Internet</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="U"> URA</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="P"> POS</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="T"> TEF</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="C"> Celular</nobr>
</td>
<td class="menu">
<nobr><input type="checkbox" name="ckbTreinamentos[]" value="F"> Fechamentos</nobr>
</td>
</tr>
</table>

At the time of $ _REQUEST [''] you can set a foreach that can be played in a string, as shown below:

if (isset($_REQUEST['ckbTreinamentos'])) {          
        $qt = count($_REQUEST['ckbTreinamentos']);
        $k = 1;         
        foreach ($_REQUEST['ckbTreinamentos'] as $treinamento){             
            $v = "";
            if($k < $qt) {
                $v = ", ";
            }
            $comp .= $treinamento.$v;
            $k++;
        }
        return $comp;
    } else {
        $comp = null;
    }
    
answered by 18.09.2014 в 15:39
3

One thing I may not have seen is if you do not pass any value, for example:

<input type="checkbox" name="meu_checkbox" checked="checked">

For example, if you post by post, in php you will get it as well

if (isset($_POST['meu_checkbox']) && $_POST['meu_checkbox'] == 'on')
{
    echo "Meu Checkbox está marcado";
}

You need to check if the value exists because if the user does not check the box, nothing will be passed and this will give you an error, and when no value is passed, the value is on

The error that will occur if you do not check for isset is this:

  

A PHP Error was encountered

     

Severity: Notice

     

Message: Undefined index: my_checkbox

    
answered by 18.09.2014 в 15:58
2

In the array of $_REQUEST (I do not know if the method of your form is GET or POST ), just check if the key of the name of your checkbox is there, with the corresponding value.     

answered by 13.02.2014 в 17:39
0

If on your form, you have for example:

<input type="checkbox" name="status" value="ativo">

When submitting the form, if the field is NOT marked, it will not be sent to your server.

Soon it would be like you trying to access an index in an array without it existing or accessing an index name in a nonexistent associative array.

If it is checked, you can access its value normally as an array.

In the PHP page that will receive the data sent by the form:

The global variables can be used: $ _POST, $ _GET or $ _REQUEST;

<?php
   //Verificando se o "índice associativo 'status'" foi enviado pelo formulário 
   $statusRecebido = (isset($_REQUEST['status']))?$_REQUEST['status']:'inativo';

   //Se o checkbox foi marcado, virá o valor contido no seu atributo 'value', ou seja, 'ativo'. 
   //caso não venha será atribuído o valor 'inativo' por exemplo.

   echo $statusRecebido."<br/>";

I hope I have helped better in understanding.

    
answered by 20.11.2018 в 01:49