How to get value from a checkbox

3

When I submit the form the input does not return the value of checkbox and says $_POST['newsconf'] does not exist.

HTML

<input type="checkbox" id="newsconf" name="newsconf" value="1"/>
<label for="newsconf">Assinar newsletter</label>

What am I doing wrong to not be getting the value of checkbox ?

    
asked by anonymous 31.12.2014 / 23:15

2 answers

4

I ran a test and it worked as it should. You made a statement in the comment that I do not believe is actually happening:

<form action="index.php" method="post">
<input type="checkbox" id="newsconf"  name="newsconf" value="1"/>
<input type="submit" name="submit" value="Ok"/>
</form>

PHP

<?php
if(isset($_POST['newsconf']) && $_POST['newsconf'] == '1') {
    echo "checkado";
} else {
    echo "não checkado";
}     
?>

When the field is not marked it is not sent by the form, so you need to check if it exists to see if it is checked.

If this is not the case, there is no way to know what the problem was with the question.

    
31.12.2014 / 23:36
2

As a complement, another solution that aims to ensure that the form will always send us a value for checkbox whether it is checked or not, it passes by applying a input hidden in the form to give us a value by default:

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

In this way, in PHP we always have the entry in the matrix that corresponds to the method of submitting the form, below an example for method="POST" :

$querNewsletter = $_POST["newsconf"]; // vai otber 0 se não marcou ou 1 se marcou

Notes: To work as described above there are two things to keep:

  • The hidden field must be before the field that the user uses, so that the user field subscribes the value of the hidden field if the user actually marks the checkbox .

  • The hidden field must have the value in the name attribute equal to what we use in checkbox .

  • 01.01.2015 / 00:18