Berna
Berna

Reputation: 39

How to get info from form to php of a checkbox

I got this form:

<form name="formx" id="formx" action="var.php" method="POST">
  <input type="checkbox" name="f_check1"> Check 1
  <input type="checkbox" name="f_check2">Check 2
  <input name="f_register" value="Register" type="submit">
</form>

And on the var.php file I have:

   <?php
   if($_POST['f_register'] == "Register") {
     $check1 = $_POST['f_check1'];
     $check2 = $_POST['f_check2'];
     }

 echo $check1. "<br>" ;
 echo $check2;
?> 

And when i fill the form and go to the var.php, i only get results if the checkbox is on, and i want it to say "true" if checked and "false" if not.

P.S: I'm using XAMPP to run the website.

Upvotes: 0

Views: 83

Answers (4)

user3660952
user3660952

Reputation:

Try this?

<form name="formx" id="formx" action="var.php" method="POST">
<input type="checkbox" name="f_check1"> Check 1
<input type="hidden" name="f_check1" value="0" />
<input type="checkbox" name="f_check2">Check 2
<input type="hidden" name="f_check2" value="0" />
<input name="f_register" value="Register" type="submit">
</form>

Edited as requested:

The hidden field with the same name will be passed if the checkbox is not checked.

Upvotes: 1

Jhonny Mesquita
Jhonny Mesquita

Reputation: 144

Use this block:

 <?php
   if($_POST['f_register'] == "Register") {
     $check1 = isset($_POST['f_check1']);
     $check2 = isset($_POST['f_check2']);
     }

if($check1) echo '<br>check1 true';
else echo 'check1 false';
if($check2) echo '<br>check2 true';
else echo '<br>check2 false';
?> 

Upvotes: 1

j08691
j08691

Reputation: 207901

Unchecked checkboxes aren't sent to the server. So you can account for that with:

 $check1 = isset($_POST['f_check1']) ? true:false;
 $check2 = isset($_POST['f_check2']) ? true:false;

Upvotes: 1

dokgu
dokgu

Reputation: 6040

$check1 = isset($_POST['f_check1']);
$check2 = isset($_POST['f_check2']);

Upvotes: 1

Related Questions