I'm using XAMPP server & trying to add a simple checkbox into a edit page.
But after submitting & refreshing the page the checkbox
does not stay checked or unchecked
Can someone help me with this
<input id="dating"
class="switch"
type="checkbox"
value="1"
name="dating"
<?php echo $dating== "1" ? " checked" : ""; ?> >
<label for="switch"></label>
<input id="dating" class="switch" type="checkbox" name="dating" value="1" <?php if(isset($_POST['dating'])) echo 'checked'; ?> />
You should var_dump($dating) to confirm if the statement $dating== "1" evaluates the way you intend it to...
use localStorage for it.
HTML Code:
<input type="checkbox">
JS Code:
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
Related
I am using method= "GET", I have 2 radio buttons.I want to retain the selected radio button value even After clicking my submit button.
This is something I have tried, but yet does not work. Can any1 plz help me . Thank u in advance.
VEG<input type="radio" name="choice" <?php if (isset($_GET['choice']) && $_GET['choice']=="veg") echo 'selected="seleceted"';?>value="veg" >
Nonveg<input type="radio" name="choice" <?php if (isset($_GET['choice']) && $_GET['choice']=="nonveg") echo 'selected="seleceted"';?>value="nonveg" ></td>
Plz help me solve this.
Right Practice
<?php
$vegChecked = NULL;
$nonvegChecked = 'checked="checked"';
if(isset($_GET['choice'])) {
if($_GET['choice'] == 'veg') {
$vegChecked = 'checked="checked"';
$nonvegChecked = NULL;
} else if($_GET['choice'] == 'nonveg') {
$vegChecked = NULL;
}
}
?>
VEG <input type="radio" name="choice" <?php echo $vegChecked;?> value="veg" />
Nonveg <input type="radio" name="choice" <?php echo $nonvegChecked;?> value="nonveg" />
Instead of selected="selected" try using checked.
For example :-
<input type="radio" name="choice" <?php if (isset($_GET['choice']) && $_GET['choice']=="nonveg") echo 'checked'; ?>value="nonveg" >
Try this,
VEG<input type="radio" name="choice" <?php if (isset($_GET['choice']) && $_GET['choice']=="veg") echo 'checked="checked"';?> value="veg" >
Nonveg<input type="radio" name="choice" <?php if (isset($_GET['choice']) && $_GET['choice']=="nonveg") echo 'checked="checked"';?> value="nonveg" >
Use Ajax instead of form submission to avoid refreshing of the page Or Set the value of radio button in session while executing form submission PHP. like session_start();
$_SESSION['choice'] = $_GET['choice'];
then check the value using if condition to set selected button.
form :
<label for="sitecheck">
<span style="font-weight:bold;">סגור אתר זמנית:</span>
</label>
<input name="sitecheck" type="checkbox" id="sitecheck" onClick="validateSitec();" <?php if($data['sclosed'] == 'true'){echo 'checked = "checked"';}; ?> /><span style="font-weight:bold;">סגור אתר ורשום הודעה זמנית</span><br>
<input type="text" name="closedmsg" id="closedmsg" style="width:440px;height:120px;<?php if($data['sclosed'] == 'true'){echo '';}else{ echo 'display:none;'; }; ?>" value="<?php echo $data['csitemsg']; ?>" /><span id="sitemsg_error"></span>
php :
if(isset($_POST['sitecheck']))
{
$sitecheck = 'true';
}else{
$sitecheck = 'false';
}
any idea why its not working ?
i trying to determine if checked or not and update on Database.. anyidea why its alwys true even if i uncheck?
EDIT :
fixed by my own was ajax post wrong , i should val the checked box like that :
var sitecheck = $('#sitecheck').is(':checked') ? $('#sitecheck').val() : '' ;
so now working thanks.
Add value param to your checkbox. Value will be send if checkbox is checked.
<input name="sitecheck" type="checkbox" id="sitecheck" value="1" ....
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
I'm trying to figure out how to make the logic in the following form work. Basically if either of the first two radio buttons is checked, make the hidden input named categories have a value of vegetables. Else, make the hidden input named categories have a value of fruits.
I'm not sure if this should be done with PHP or JavaScript, but if it is done with PHP I think the form would have to be submitted to itself to be pre-processed and then the collected, pre-processed information would be sent to external_form_processor.php. If this is how you do it, what would be the PHP code that I need to use to make it work?
<?php
if($_POST["food"]=="carrots" || $_POST["food"]=="peas") {
$category = "vegetables";
} else {
$category = "fruits";
}
?>
<form name="food_form" method="post" action="external_form_processor.php" >
<fieldset>
<input type="radio" id="carrots" name="food" value="carrots" />
<input type="radio" id="peas" name="food" value="peas" />
<input type="radio" id="orange" name="food" value="orange" />
<input type="radio" id="apple" name="food" value="apple" />
<input type="radio" id="cherry" name="food" value="cherry" />
</fieldset>
<input type="hidden" name="categories" value="<?php $category ?>" />
</form>
If using jQuery would be easier, how could I call the variable as the value of the hidden input if I use the following in the head of the page?
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
});
});
Any help with this would be greatly appreciated. Thanks!
I think jQuery would work perfect for you, you just need to pass the category value to the input field:
$(function(){
$('input[name=food]').click(function(){
var selected_id = $('input[name=food]:checked').attr('id');
if (selected_id == 'carrots' || selected_id == 'peas') {
var category = "vegetables";
} else {
var category = "fruits";
}
$('input[name=categories]').val(category);
});
});
I would set the category in PHP when the form is submitted.
//validate inputs... always
$food = "";
if(isset($_GET['food'])){
$food = preg_replace("/[^a-zA-Z]+/", "", $_GET['food']);
}
$category = ($food=="peas"||$food=="carrots")?"vegetables":"fruits";
For usability purposes I like to set up my form fields this way:
<?php
$username = $_POST['username'];
$message = $_POST['message'];
?>
<input type="text" name="username" value="<?php echo $username; ?>" />
<textarea name="message"><?php echo $message; ?></textarea>
This way if the user fails validation, the form input he entered previously will still be there and there would be no need to start from scratch.
My problem is I can't seem to keep check boxes selected with the option that the user had chosen before (when the page refreshes after validation fails). How to do this?
My first suggestion would be to use some client-side validation first. Maybe an AJAX call that performs the validation checks before continuing.
If that is not an option, then try this:
<input type="checkbox" name="subscribe" <?php echo (isset($_POST['subscribe'])?'checked="checked"':'') ?> />
So if subscribe is = 1, then it should select the box for you.
For Example, consider the following code for checkbox :-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
Then, this would remember the checkbox of "PHP" if it is checked, even if the validation for the page fails and so on for "n" number of checkboxes as shown below:-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("HTML", $_POST["course"]))) {
echo "checked";
} ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("CSS", $_POST["course"]))) {
echo "checked";
} ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("Javascript", $_POST["course"]))) {
echo "checked";
} ?> value="Javascript" />
And most importantly, do not forget to declare the "course" variable as an array at the start of the code as shown below :-
$course = array();
I have been battling how to create sticky check box (that is able to remember checked items any time you visit the page). Originally, I get my values from a database table. This means that my check box value is entered to a column on my db table.
I created the following code and it works just fine. I did not want to go through that whole css and deep coding, so...
CODE IN PHP
$arrival = ""; //focus here.. down
if($row['new_arrival']==1) /*new_arrival is the name of a column on my table that keeps the value of check box*/
{$arrival="checked";}// $arrival is a variable
else
{$arrival="";};
echo $arrival;
<b><label for ="checkbox">New Arrival</label></b>
<input type="checkbox" name ="$new_arrival" value="on" '.$arrival.' /> (Tick box if product is new) <BR><BR>
<input type="checkbox" name="somevar" value="1" <?php echo $somevar ? 'checked="checked"' : ''; ?>/>
Also, please consider sanitising your inputs, so instead of:
$somevar = $_POST['somevar'];
...it is better to use:
$somevar = htmlspecialchars($_POST['somevar']);
When the browser submits a form with a checked checkbox, it sends a variable with the name from the name attribute and a value from the value attribute. If the checkbox is not checked, the browser submits nothing for the checkbox. On the server side, you can handle this situation with array_key_exists(). For example:
<?php
$checkedText = array_key_exists('myCheckbox', $_POST) ? ' checked="checked"' : '';
?>
<input type="checkbox" name="myCheckbox" value="1"<?php echo $checkedText; ?> />
Using array_key_exist() avoids a potential array index undefined warning that would be issued if one tried to access $_POST['myCheckbox'] and it didn't exist.
You may add this to your form:
<input type="checkbox" name="mycheckbox" <?php echo isset($_POST['mycheckbox']) ? "checked='checked'" : "" ?> />
isset checks if a variable is set and is not null. So in this code, checked will be added to your checkbox only if the corresponding $_POST variable has a value..
My array has name="radioselection" and value="1", value="2", and value="3" respectively and is a radio button array... how to I check if the radio value is selected using this code
I tried:
<?php echo (isset($_POST['radioselection']) == '1'?'checked="checked"':'') ?> />