Remembering Form Checkbox State With Initial Default Value - php

I've got a form with a checkbox. When a user first visits the page, I want the checkbox to be 'checked'. However, if they uncheck the box and then submit the page, I want it to remain unchecked (and to remain checked if they submit the page with it checked).
To determine when it has been checked and the form submitted, I'm currently doing:
<input type='checkbox' class='seeAll' name='seeAll' value='true' <?php if ($_POST['seeAll'] == 'true') echo checked; ?>>
This works great for leaving the box checked when needed, however, how would I go about ensuring it stays unchecked if they submit it that way, while also being checked if they revisit the page (such as by re-entering the URL)?
Thanks!

I don't know why it took me so long to come up with this answer, but after struggling with this, I realized I could just check the value of the checkbox via the $_POST, as I was doing before and could check if the user arrived at the page by some means other than the submit button by doing this:
<?php if(($_POST['seeAll'] == 'true') || !isset($_POST['submit'])) echo checked; ?>
If the user submitted the form, than isset($_POST['submit']) will be true and so if that's the case and $_POST['seeAll'] is empty, them obviously the user submitted an unchecked box. If isset($_POST['submit']) is false, then the user arrived on the page without submitting the form and I should check the checkbox as the 'default'.
So then my whole <input> tag looks like this:
<input type='checkbox' class='seeAll' name='seeAll' value='true' <?php if(($_POST['seeAll'] == 'true') || !isset($_POST['submit'])) echo checked; ?>>
Works just as I need!

NOTE:: This is differs from OP's question because it will remember the value of the checkbox even if the user goes away from the page (say, to www.facebook.com) and then back to the page. The OP wanted it to only remember the value of the checkbox when the page was posted to.
If you want a non permanent method you can use $_SESSION :
<?php
if (!isset($_SESSION)) {
session_start();
}
if ($_POST['seeAll'] == 'true' || !isset($_SESSION['seeAll'])) {
$_SESSION['seeAll'] = true;
} else {
$_SESSION['seeAll'] = false;
}
?>
<form method="POST">
<input type='checkbox' class='seeAll' name='seeAll' value='true'
<?php if ($_SESSION['seeAll']) echo 'checked'; ?>
/>
<input type='submit'/>
</form>
see: http://php.net/manual/en/session.examples.basic.php

One solution is to use both $_SESSION[""] and $_POST[""].
(See explanation and code below)
EXPLANATION
If $_SESSION["loadcount"] is not set, set it to 0.
With each if (isset($_POST["submit"], increase $_SESSION["load count"] by +1.
In the 'checked' option of the input type="checkbox", echo PHP. If if ($_SESSION["loadcount"] == 0) echo 'checked'. (Sets the checkbox to an initially checked state.)
Else, if (isset($_POST["agree"] echo 'checked', to remember the state checked by the user. (Remember the checked state set by user.
CODE
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php // session_firstload.php
// Check if $_SESSION is not set, set $_SESSION loadcount to 0
if (!isset($_SESSION["loadcount"]))
$_SESSION["loadcount"] = 0;
// When the user submits using POST Method
if (isset($_POST["submit"]))
{
// Increase $_SESSION["loadcount"] by +1
$_SESSION["loadcount"] = $_SESSION["loadcount"] + 1;
}
// Echoing for Debugging / Understanding
echo $_SESSION["loadcount"];
?>
<form action="session_firstload.php" method="post">
<input id="agree" type="checkbox" name="agree"
<?php
// If Check the Checkbox is $_SESSION["loadcount"] == 0
// Else 'remember' with (isset($_POST["agree"]
if ($_SESSION["loadcount"] == 0)
echo "checked";
else
{
if (isset($_POST["agree"]))
echo "checked";
}
?>
>I Agree<br>
<input type="submit" name="submit">
</form>
</body>
</html>

Related

Input checkbox when i edit user no change

When i want to edit my user on inactive is it no working, but when i editing my users to inactive to active, it is working.
This is my PHP code: https://pastebin.com/iBaDxH2u
<input class="form-control" type="checkbox" name="actif" id="actif" value="<?php echo $userinfo['actif']; ?>" <?php if ($userinfo['actif'] == "1") { echo "checked"; } ?>>
<input type="hidden" name="actif" value="1" />
I dont solve the problem...
Thx
This sounds like it has something to so with how checkboxes work. When you submit the form, if the checkbox is ticked then the page you submit the form to will receive [actif] => on. If you submit with the checkbox unticked then the page will not receive [actif] => off, it will receive an empty array []. actif will not be set. Something like this might make it more obvious what is going on.
<?php
if (isset($_GET['actif']) && $_GET['actif']=="on")
{
echo ("The box was ticked");
$ticked = 'checked';
}
else
{
echo ("The box was not ticked");
$ticked = '';
}
echo ("<pre>");
print_r($_GET);
?>
<form>
Actif <input type='checkbox' name='actif' id='actif' <?=$ticked?>>
<button type='submit'>Click me</button>
</form>

PHP Radio Buttons - Keep The Values in The Form after an Error

I'm building a contact page with email, name, etc. in HTML with PHP. I have radio buttons on my contact page as well. If the user submitted their name and checked a radio button but forgot to put an email in, the form processing page will flipped them back to the contact page with an error. I'm able to have my contact keep the values put in for their name (and email if user inputs it), but it does not keep the value checked in the radio button.
I'm new to PHP, so I bet it's a silly error on my part. Here's what I have for my Name Input:
Your Name:
<input type="text" name="name" <?php
if (isset($form['name'])) {
echo 'value="';
echo htmlentities($form['name']);
echo '"';
}
?>/>
I tried to do something similar to my Radio. Here's what I have for my Radio:
Are you New to our Business?<br>
<input type="radio" name="customer" value ="yes" <?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
Yes, I am!<br>
<input type="radio" name="customer" value="no"<?php
if (isset($form['customer'])) {
echo 'value="';
echo htmlentities($form['customer']);
echo '"';
}
?>/>
No, I am a returning customer!
I'm storing the values on the user input in an array called $form - that's why I have ($form['name]). I would like to it to continue doing that. Some other responses I have researched simply have an isset without the array part.
Hopefully I've provided enough information... Thanks for your help!
You need to do it like this:
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked="checked"';
}
and
if (isset($form['customer']) && $form['customer'] == "no") {
echo 'checked="checked"';
}
You need to change the if-conditional to the following:
<?php
if (isset($form['customer']) && $form['customer'] == "yes") {
echo 'checked';
}
?>/>
Replace the "yes" with "no" for the No part.

keeping checked checkbox state unless unchecked

I had asked this question but did not get a solution. By short explanation I would like the checked checkboxes to stay checked unless unchecked by the user: on page refresh.
I am able to keep the boxes checked on page refresh but when the page id changes(I have pagination) like index.php?page=2 the boxes get unchecked so is there a way that I can get the boxes to stay checked unless unchecked even if the page id changes?
I am displaying results from database and the user can filter results. If the user clicks on the next page for more results I would like to keep the checked boxes stay checked so that I can show filtered results from page 2. I really need help. Thanks
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" <?=(isset($_POST['sa'])?' checked':'')?>/>Samsung<br>
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
I have tried this jquery function along with the above one but it doesn't work.
$("input.checkbox").each(function() {
var mycookie = $.cookie($(this).attr('name'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$("input.checkbox").change(function() {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});
I think this is what you need:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_POST['sa'] == 'yes')? ' checked="checked"':'' ?>/>Samsung<br>
The proper mark-up being
checked="checked"
to get that to stay active based on your condition.
This only occurs if you are continuing through other pages WITH the form being used to get to them. If you only expect people to use the form once, you should set a SESSION or GET variable to carry that value through other pages without the use of the form.
So, for example, keep the form almost the same, except change your condition and include this in your header, before you spit out the form -
<?php
session_start();
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
then make you're condition for spitting out checked:
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
and include a hidden input to only check if the checkbox has changed.
<input type="hidden" name="changeit" />
that way, the condition for setting the session is only checked if the form checkbox was checked or unchecked... so your whole structure should look something like this -
<?php session_start(); ?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</HEAD>
<BODY>
<?php
if(isset($_POST['changeit'])) {
if( $_POST['sa'] == 'yes') {
$_SESSION['checked'] = true;
} else {
$_SESSION['checked'] = false;
}
}
?>
<form id="form" method="post" action="">
<input type="checkbox" name="sa" class="checkbox" value="yes"
<?php echo ($_SESSION['checked'] == true)? ' checked="checked"':'' ?>/>Samsung<br>
<input type="hidden" name="changeit" />
</form>
<script>
$(document).ready(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
</BODY>
</HTML>
The fundamental note is that POST variables will not transfer over from page to page if the form isn't being used. The "action" is not called, thus the post is not sent. You have to use either COOKIES or SESSIONS or GET variables to have this cross over pages without the use of the form every time.
RCNeil's answer is correct, in that if the post key 'sa' is set, the checkbox will be checked="checked".
To expand on his answer, It doesn't have to be from a post value, it can be pulled from the database, or anywhere really. It just needs to return a boolean (True/False). The following would also work:
//Some logic
$YourVariable = true; //for example
//Then the checkbox conditional
<input type="checkbox" name="sa" class="checkbox"
<?=($YourVariable)?' checked="checked"':'')?>/>Samsung<br>
Will return as the checked="checked" and the checkbox marked by default. (Unless, bool false)
<input type="checkbox" name="sa" class="checkbox" checked="checked" value="forever"
<?=(isset($_POST['sa'])?:'')?>/>Samsung<br>
I guess this should work

How to escape other codes - php

i have a form with action='#'
that outputting some inputs
and a statement when the submit button clicks
if($_POST['edit'] == 'Edit')
{
manipulation here
with printout
}
what happen here is the output of the MAIN FORM
and the output of the IF STATEMENT print out when SUBMIT button is click
what i want is, when the SUBMIT button is click, ONLY the PRINTOUT on IF STATEMENT will shows.
Have you tried extending the if statement with an else - one or the other type of situation?
//when form is submitted
if($_POST['edit'] == 'Edit')
{
manipulation here
with printout
}
//when form not submitted
else
{
//display form
}
If I understand correctly, you do not want to display the form after it has been submitted. If that is the case, you can check to see if one of the values submitted by the form is set or not and display the original form based on that.
Here is an example:
<?php if( !isset($_POST['edit']) ): ?>
<form action="#">
<input type="text" name="edit" />
...
<input type="submit" value="Submit" />
</form>
<?php else: ?>
Display other information.
<?php endif; ?>

Disable all input buttons on page if no PHP session exists

I'm doing a site with a voting system. What i want is to disable all input buttons (the ability to vote) if the user isnt logged in (ie. a session doesnt exist). How do i do a check in PHP at the top of the page and then allow/disallow the input buttons? Would i use CSS or jQuery?
Somewhere in the code check if the session is not set:
if(!isset($_SESSION['some_key'])){
$disable = true;
}else{
$disable = false;
}
Then, in the html:
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 1
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 2
<input type="radio" name="" value=""<?=($disable ? " disabled=\"disabled\"" : "");?>/> Vote 3
But you still have to check at the serverside before you accept the vote, if the person has voted before, because this form can be edited easily to post the data again and again.
<?php if(!isset($_SESSION['logged']))
{
echo "<script language=\"javascript\">";
echo "$(document).ready(function()
{
$('input[type=submit]').each(function() { this.attr('disabled', 'disabled') });
});</script>"
}
?>
You should dynamically generate a correct HTML code. Something like this:
<?php if(isset($_SESSION['logged'])): ?>
<form> voting form </form>
<?php else: ?>
<p>Sign in to vote</p>
<?php endif ?>
You should also check whether user is logged in before you process a form:
if (isset($_SESSION['logged']) && isset($_POST['vote'])) {
// process form
}

Categories