Question

I have a simple form that has a checkbox on it.

If a user selects it and the submits the form (the form posts back to the same page) - how can I ensure that the checkbox is selected when the page re-loads?

Was it helpful?

Solution

if($_POST["name_of_the_checkbox"]) { /*TODO*/ }

OTHER TIPS

Say you have the check box inputs of:

<input type="checkbox" name="action" value="Option 1" >1;
<input type="checkbox" name="action" value="Option 2" >2;
<input type="checkbox" name="action" value="Option 3" >3;

You want to store the values in the $_POST variable like so:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (empty($_POST["action"])){
    $Q1Err = "<br />Please Select Atleast One";
} else {
    $Q1 = ($_POST["action"]);
}

As always you should declare your variables empty before the start of any page:

$Q1 = ""
$Q1Err = ""

Then go back to the input tags and input php tags within:

<input type="checkbox" name="action" <?php if (isset($Q1) && $Q1=="Option 1") echo "checked";?> value="Option 1" >1;
<input type="checkbox" name="action" <?php if (isset($Q1) && $Q1=="Option 2") echo "checked";?> value="Option 2" >2;
<input type="checkbox" name="action" <?php if (isset($Q1) && $Q1=="Option 3") echo "checked";?> value="Option 3" >3;
<span><br /><?php echo $Q1Err;?></span> 

If you have any other questions, please let me know. I might have forgotten something...but this should be a good start.

First of all, set action attribute in form tag for sending data to custom php script. If it is empty then form send data to the same page (reload). Second, for checking what are incoming to script use:

<?=var_export($_REQUEST)?>

before or after form definition.

Try this

<input type="checkbox" name="check_box_name" <?php if (isset($_POST['check_box_name'])) { echo 'checked="checked"'; } ?>>

I would simply let the user post the form, and at the location where you define your form have the following code:

<?php
if(isset($_POST["checkbox-name"])) { 
    echo "<input type="checkbox" value="value" name="Please check me"></input>";
} else {
    echo "<input type="checkbox" value="value" name="Please check me" checked></input>";
} 
?>

Note that this is only to have some clarity, you can naturally also make this a bit shorter by only putting the php tags around the actually "checked" parameter of the input field as such:

<input type="checkbox" value="value" name="Please check me"
<?php 
if(isset($_POST["checkbox-name"])) { 
    echo "checked";
}
?>
></input>

This will put checked at the end of the input and would result in the same end output

<input type="checkbox" name="x" <?php echo isset($_POST['x']) ? 'checked' : ''; ?>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top