send checkbox value in PHP form
Solution 1:
Here's how it should look like in order to return a simple Yes
when it's checked.
<input type="checkbox" id="newsletter" name="newsletter" value="Yes" checked>
<label for="newsletter">i want to sign up for newsletter</label>
I also added the text as a label, it means you can click the text as well to check the box. Small but, personally I hate when sites make me aim my mouse at this tiny little check box.
When the form is submitted if the check box is checked $_POST['newsletter']
will equal Yes
. Just how you are checking to see if $_POST['name']
,$_POST['email']
, and $_POST['tel']
are empty you could do the same.
Here is an example of how you would add this into your email on the php side:
Underneath your existing code:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
Add:
$newsletter = $_POST['newsletter'];
if ($newsletter != 'Yes') {
$newsletter = 'No';
}
If the check box is checked it will add Yes
in your email if it was not checked it will add No
.
Solution 2:
If the checkbox is checked you will get a value for it in your $_POST
array. If it isn't the element will be omitted from the array altogether.
The easiest way to test it is like this:
if (isset($_POST['myCheckbox'])) {
$checkBoxValue = "yes";
} else {
$checkBoxValue = "no";
}
For your code, add it immediately below the other preprocessing:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
$newsletter = "yes";
} else {
$newsletter = "no";
}
You'll also need to change the HTML slightly. Change this line:
<input type="checkbox" name="newsletter[]" value="newsletter" checked>i want to sign up for newsletter<br>
to this:
<input type="checkbox" name="newsletter" value="newsletter" checked>i want to sign up for newsletter<br>
^^^ remove square brackets here.
Solution 3:
if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
//checked
}