How to get value from a checkbox

Asked

Viewed 213 times

4

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

HTML

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

What I’m doing wrong so I’m not getting the value of checkbox?

  • The same happens if the checkbox is marked or not?

  • yes, it’s the same

  • 1

    It would be nice to put the form and a minimum of script PHP to see if the problem is not elsewhere.

  • $_POST['newsconf'] will only exist if the checkbox is checked, use isset to know whether or not he was marked.

2 answers

5


I did a test and it worked as it should. You made a statement in the comment that I don’t 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";
}     
?>

I put in the Github for future reference.

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

If this is not the case, there is no way of knowing what the problem is with what was asked in the question.

3

As a complement, another solution that aims to ensure that the form will always send us a value for the checkbox whether it is marked or not, it involves applying a input hidden in the form to provide us with a default value:

<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 input in the matrix that corresponds to the form submission method, below an example for method="POST":

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

Notes: For it to work as described above there are two attentions to have:

  1. The hidden field has to be before the field the user uses, so that the user field subscribes the value of the hidden field if the user actually marks the checkbox.

  2. The hidden field has to have the value in the attribute name same as the one we use in checkbox.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.