keeping checked checkbox state unless unchecked - php

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

Related

how to uncheck checkboxes when another is checked?

im kinda trying to get into programming in general and was wondering how to uncheck / check with updating the array-
like as soon as someone checks a 2nd checkbox it should uncheck the first option and update the search (w the new data)- im a mere beginner and kinda lost rn so would appreciate any form of help
<form action="index.php" id="form1" name="form1" method="get">
<?php $i = 0; foreach ($row_page_nav_kategorie as $row_page_nav_kategorie) { ?>
<label class="checkbox-container">
<input <?php if (strpos($url,$row_page_nav_kategorie['typ']) == true) {echo 'checked="checked"';}?>
type="checkbox"
class="checkmark"
name="hotelKategorie[]"
id="ckb5"
value="<?php echo $row_page_nav_kategorie['typ']; ?>"
onclick="kategorie(<?php echo $i ?>);"
onchange="submit()"/>
<?php echo $row_page_nav_kategorie['typ']; $i++;?>
</label>
<?php } ?>
</form>
You should use radio buttons, but if you want to overwrite checkbox functionality below code will take care of it, I have added a common class on your inputs:
function checkboxClick(obj) {
var cbs = document.getElementsByClassName("checkkbox-option");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo
First of all welcome to the community!
As for your question, there is multiple ways to handle this, one of wich is as followed:
In HTML there's an attribute called radio wich you can add to your input by using type='radio'. In a set of radio buttons, only one can be checked at any time. If you then want to immedietely submit your form, you can use something like onChange='this.form.submit()'. This will submit your form when the value is changed, such as pressing on a different radio button.
Something to keep note of is that the attribute onChange is case sensitive as far as i'm aware. You were heading in the right direction with onchange="submit(), but your code doesn't know what to submit. this.form.submit() will submit the form that the element is in.
Use Radio Buttons or use JavaScript on your page to dynamically uncheck other checkboxes when you click on one.
If you want to dynamically update the page content with the new search results you should also look into AJAX which basically means you will call PHP functions from JavaScript code and those will return JSON arrays that you can exploit to modify your page's DOM.
Try THIS
HTML:
<label><input type="checkbox" name="check1" class="checkbox" /> CheckBox1</label>
<label><input type="checkbox" name="check2" class="checkbox" /> CheckBox2</label>
<label><input type="checkbox" name="check3" class="checkbox" /> CheckBox3</label>
<label><input type="checkbox" name="check4" class="checkbox" /> CheckBox4</label>
jQuery:
$(".checkbox").change(function() {
$(".checkbox").prop('checked', false);
$(this).prop('checked', true);
});
if you want to uncheck the selected checkbox
$(".checkbox").change(function() {
$(".checkbox").not(this).prop('checked', false);
});
hope this helps, thanks !!!

How can I check if a checkbox is NOT checked

I need to check whether checkbox is checked or not. Normally I would do it like this:
<?php
$checked = isset($_POST['checkbox']);
?>
But I don't know what is the name. More at screenshot (I'm using Laravel 4).
Screenshot
You simply can't. The data for unchecked checkboxes are not send to the server.
You could do a workaround with javascript where the JS appends some hidden fields before submit with the nonchecked boxes
Supposedly you should know what the list of checkboxes is/was that you asked the user to check. Checked checkboxes are submitted to the server, unchecked ones aren't. You can calculate the difference between these two lists.
if you are using jquery, and you know the id of the checkbox,
then, you can detect with following code:
var isChecked = $("#cbId").is(":checked");
<?php
if ( ! isset($_POST['checkbox_name']))
{
"Not checked";
}
?>
If checkbox didn't check - you will not have this variable in $_REQUEST.
<form action="">
<input type="checkbox" name="ch1"/>
<input type="checkbox" name="ch2"/>
<input type="checkbox" checked="checked" name="ch3"/>
<input type="submit" name="Post" value="Post">
</form>
When you click on "Post". In backend you'll see:
<?php
if(isset($_REQUEST['ch1']))
echo 'ch1 is checked!';
if(isset($_REQUEST['ch2']))
echo 'ch2 is checked!';
if(isset($_REQUEST['ch3']))
echo 'ch3 is checked!';
?>
In my case you'll see: "ch3 is checked!".

Remembering Form Checkbox State With Initial Default Value

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>

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
}

Submit an HTML form with empty checkboxes

I have an HTML form - with PHP, I am sending the data of the form into a MySQL database. Some of the answers to the questions on the form have checkboxes. Obviously, the user does not have to tick all checkboxes for one question. I also want to make the other questions (including radio groups) optional.
However, if I submit the form with empty boxes, radio-groups etc, I received a long list of 'Undefined index' error messages for each of them.
How can I get around this? Thanks.
I've used this technique from time to time:
<input type="hidden" name="the_checkbox" value="0" />
<input type="checkbox" name="the_checkbox" value="1" />
note: This gets interpreted differently in different server-side languages, so test and adjust if necessary. Thanks to SimonSimCity for the tip.
Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.
if (isset($_POST['checkbox'])) {
// checkbox has been checked
}
An unchecked checkbox doesn't get sent in the POST data.
You should just check if it's empty:
if (empty($_POST['myCheckbox']))
....
else
....
In PHP empty() and isset() don't generate notices.
Here is a simple workaround using javascript:
before the form containing checkboxes is submitted, set the "off" ones to 0 and check them to make sure they submit. this works for checkbox arrays for example.
///// example //////
given a form with id="formId"
<form id="formId" onSubmit="return formSubmit('formId');" method="POST" action="yourAction.php">
<!-- your checkboxes here . for example: -->
<input type="checkbox" name="cb[]" value="1" >R
<input type="checkbox" name="cb[]" value="1" >G
<input type="checkbox" name="cb[]" value="1" >B
</form>
<?php
if($_POST['cb'][$i] == 0) {
// empty
} elseif ($_POST['cb'][$i] == 1) {
// checked
} else {
// ????
}
?>
<script>
function formSubmit(formId){
var theForm = document.getElementById(formId); // get the form
var cb = theForm.getElementsByTagName('input'); // get the inputs
for(var i=0;i<cb.length;i++){
if(cb[i].type=='checkbox' && !cb[i].checked) // if this is an unchecked checkbox
{
cb[i].value = 0; // set the value to "off"
cb[i].checked = true; // make sure it submits
}
}
return true;
}
</script>
To add to fmsf's code, when adding checkboxes I make them an array by having [] in the name
<FORM METHOD=POST ACTION="statistics.jsp?q=1&g=1">
<input type="radio" name="gerais_radio" value="primeiras">Primeiras Consultas por medico<br/>
<input type="radio" name="gerais_radio" value="salas">Consultas por Sala <br/>
<input type="radio" name="gerais_radio" value="assistencia">Pacientes por assistencia<br/>
<input type="checkbox" name="option[]" value="Option1">Option1<br/>
<input type="checkbox" name="option[]" value="Option2">Option2<br/>
<input type="checkbox" name="option[]" value="Option3">Option3<br/>
<input type="submit" value="Ver">
Use this
$myvalue = (isset($_POST['checkbox']) ? $_POST['checkbox'] : 0;
Or substituting whatever your no value is for the 0
We are trouble on detecting which one checked or not.
If you are populating form in a for loop, please use value property as a data holder:
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i ?>"
<?endfor;?>
If submit form you'll get order numbers of checkboxes that checked (in this case I checked 3rd and 4th checkboxes):
array(1) {
["active"]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
When you are processing form data in loop, let's say in post.php, use following code to detect if related row is selected:
if(in_array($_POST['active'] ,$i))
$answer_result = true;
else
$answer_result = false;
Final code for testing:
<?php if (isset($_POST) && !empty($_POST)):
echo '<pre>';
var_dump($_POST);
echo '</pre>';
endif;
?>
<form action="test.php" method="post">
<?php for($i=1;$i<6;$i++):?>
<input type="checkbox" name="active[]" value="<?php echo $i; ?>" />
<?php endfor;?>
<button type="submit">Submit</button>
</form>
Although many answers were submitted, I had to improvise for my own solution because I used the customized check-boxes. In other words, none of the answers worked for me.
What I wanted to get is an array of check-boxes, with on and off values. The trick was to submit for each check-box on/off value a separator. Lets say that the separator is ";" so the string you get is
;, on, ;, ;, ;
Then, once you get your post, simply split the data into array using the "," as a character for splitting, and then if the array element contains "on", the check-box is on, otherwise, it is off.
For each check-box, change the ID, everything else is the same... and syntax that repeats is:
<div>
<input type="hidden" name="onoffswitch" class="onoffswitch-checkbox" value=";" />
...some other custom code here...
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch1" checked>
</div>
EDIT: instead of the ";", you can use some KEY string value, and that way you will know that you did not mess up the order, once the POST is obtained on the server-side... that way you can easily create a Map, Hash, or whatever. PS: keep them both within the same div tag.

Categories