Related
How to read if a checkbox is checked in PHP?
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array():
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>
Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
PHP Code: (use for Add/Edit pages)
$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
A minimalistic boolean check with switch position retaining
<?php
$checked = ($_POST['foo'] == ' checked');
?>
<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>
when you check on chk2 you can see values as:
<?php
foreach($_POST as $key=>$value)
{
if(isset($key))
$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>
in BS3 you can put
<?php
$checked="hola";
$exenta = $datosOrdenCompra[0]['exenta'];
var_dump($datosOrdenCompra[0]['exenta']);
if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
$checked="on";
}else{
$checked="off";
}
?>
<input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Wordpress have the checked() function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description
Compares the first two arguments and if identical marks as checked
Parameters
$checked
(mixed) (Required) One of the values to compare
$current
(mixed) (Optional) (true) The other value to compare if not just true
Default value: true
$echo
(bool) (Optional) Whether to echo or just return the string
Default value: true
Return #Return
(string) html attribute or empty string
i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
foreach ($categories as $categorie) {
echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug";
}
This way i add it to the Woocommerce tabel.
wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
<?php
if(isset($_POST['nameCheckbox'])){
$_SESSION['fr_nameCheckbox'] = true;
}
?>
<input type="checkbox" name="nameCheckbox"
<?php
if(isset($_SESSION['fr_nameCheckbox'])){
echo 'checked';
unset($_SESSION['fr_nameCheckbox']);
}
?>
you should give name to your input .
then which box is clicked you will receive 'on' in your choose method
Array
(
[shch] => on
[foch] => on
[ins_id] => #
[ins_start] => شروع گفتگو
[ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
[ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
[ins_message] => سلام % به کمک نیاز دارید؟
[clickgen] =>
)
i have two checked box in my form name with 'shch' and 'foch'
I have a search form with various field but i want to set a default into the url if the field is empty:
<input type="text" name="price-max" class="form-control" placeholder="Max Price" >
and when the form is submited my url looks something like this
search.php?location=location&category=Category&status=lease&price-max=
instead i want a default value so that when i submit the form with an empty price field the url should like.
search.php?location=location&category=Category&status=lease&price-max=999
(Just) Do it server-side:
$price_max = empty($_GET['price-max']) ? 999 : $_GET['price-max'];
// /\ default value
That way, when you use $price_max in your query, it will be either user input or the default value (999 - or whatever value you decide to go with).
You don't even have to mess with the url to achieve that.
The previous code is the same as:
if(empty($_GET['price-max'])){
$price_max = 999; // default value
}else{
$price_max = $_GET['price-max'];
}
Sidenotes:
You could combine the above code with trim;
There's info / example in the docs: Example #3 Assigning a default value;
You didn't show the php code, but make sure you are protected against sql-injections;
You could put your default value as placeholder in the input, just so the user 'sees' something in there.
If you want to put default value, you should define value in each input field.
<input type="text" value="defualt_value" name="price-max" class="form-control" placeholder="Max Price" >
Instead of sending the form directly, call a function to validate the form fields. In that function, check if that field is empty and then add your default value. Finally that function submits the form.
You just need to define feild default value
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value="999">
1st method
Define value attribute in your input field but this will show your default value in text field
<form method = "GET" action="search.php">
<input type="text" name="price-max" class="form-control" placeholder="Max Price" value = "<?php echo $_GET['price-max'] ? $_GET['price-max'] : 999 ?>">
<input type="submit" value="submt">
if you didn't input then it will carry price-max = 999 otherwise whatever you will type
2nd Method
Use jQuery or javascript for this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<form method = "GET" action="search.php" id="my_form">
<input type="text" name="price-max" id="price-max" class="form-control" placeholder="Max Price">
<input type="submit">
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#my_form").submit(function() {
if($("#price-max").val()=="") {
$("#price-max").val('999');
}
});
});
</script>
I have added id attribute to form and price-max field
in controller example
public function getMessages(Request $request){
$page = request('page', 1);
$limit = request('limit', 100);
$status = request('status', 'all');
$sort = request('sort', 'asc');
$id = request('id', 'asc');
$referenceId = request('referenceId', '');
$from = request('from', '');
$to = request('to', '');
$ack = request('ack', '');
.......
}
I am trying to get the value from a textbox in another page I created and the textbox is automatically set to 0 but it keeps on telling me that the index is undefined? but once you click the confirm button the value gets submitted but I want it to automatically set as 0 without having to click the button.
This is page1:
<?php
if(isset($_POST['topscart']))
{
$_SESSION['topscart']=$_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
}
?>
This is page 2:
<td>No. of Female Tops Ordered: </td>
<td><center><?php
print" ".$_SESSION['topscart'];
?>
</td>
Textbox Code in page 1:
No. of Female Tops in Your Cart: <input type="text" value="0" size="10" name="topscart" id="topscart" >
Total: <input text="text" size="10" value="0" name="topstotal" id="topstotal" >
<input type ="submit" value="Confirm Order"></button>
<input type ="reset" id="topsbutton2" name="topsbutton2" value="Cancel Order"></button>
</center>
I couldn't quite understand the purpose but you must click the button to populate the $_POST variable.
If you must, set the value to 0 and automatically get it in $_POST then you need to use JS also - on page load fill-up the "topscart" with 0, and use .click() of the button.
Hope this helps
<?php
if(isset($_POST['topscart']))
{
session_start();
$_SESSION["topscart"] = $_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
}
?>
2nd page
<?php
session_start();
echo $_SESSION["topscart"];
?>
I think you want to default the session value to 0 unless it is set by the initial form? If that is the case then update the code on page 1 to:
<?php
if(isset($_POST['topscart']))
{
$_SESSION['topscart']=$_POST['topscart'];
print"<script language=javascript>
window.location='ACCOUNT.php';
</script>";
} else {
$_SESSION['topscart'] = 0;
}
To save me making masses of edits to the rest of my code I want to make a checkbox act like a textbox.
I have the following textbox, that if a number is greater than 0 then it adds items to a basket.
<input type="textbox"
value="<? echo $item[qty]; ?>"
name="<? echo $productid."_".$product_quantity[id]."_".$product_option[id]; ?>"
/>
How can I make a checkbox act the same way? I.e If it's ticked it's value equals 1, therefore adding it to my basket. If it remains unticked then it's value equals 0, therefore ignored.
<input type="checkbox"
value="<? echo $item[qty]; ?>"
name="<? echo $productid."_".$product_quantity[id]."_".$product_option[id]; ?>"
/>
I have several of these checkboxes going down the page.
Change the value from value="<? echo $item[qty]; ?>" to value="1"
In the action of you form i.e. wishlist.php :
if(isset($_POST["name_of_checkbox"])) {
//It means check box has been ticked
$myvalue = 1;
} else {
//It means check box was not ticked
$myvalue = 0;
}
HTH
This is another approach to the question maybe this is what you need.
I would introduce a hidden field which will store/post the 0 or 1 value. We will bind an event with the checkbox that will update the value of the hidden input.
<input name="my_cb" id="my_cb" type="checkbox" value="1" />
<input type="hidden" name="my_cb_hidden" id="my_cb_hidden" value="" />
<script type="text/javascript">
$("#my_cb").click(function() {
if($("#my_cb").is(":checked")){
$("#my_cb_hidden").val($(this).val());
} else {
$("#my_cb_hidden").val(0);
}
alert($("#my_cb_hidden").val());
});
you can change the value of checkbox value from
value="<? echo $item[qty]; ?>"
to
value="1"
then if it is checked then on Submit it will automatically store 1 as a value
EDITED :
after submitting in php code do it as as you updated your question
if(isset($_POST['checkbox name']))
{
$item[qty] = 1;
}
else
{
$item[qty] = 0;
}
but this will only make the changes in the $item array's value inspite of the value your checkbox hold.
How to read if a checkbox is checked in PHP?
If your HTML page looks like this:
<input type="checkbox" name="test" value="value1">
After submitting the form you can check it with:
isset($_POST['test'])
or
if ($_POST['test'] == 'value1') ...
Zend Framework use a nice hack on checkboxes, which you can also do yourself:
Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
When using checkboxes as an array:
<input type="checkbox" name="food[]" value="Orange">
<input type="checkbox" name="food[]" value="Apple">
You should use in_array():
if(in_array('Orange', $_POST['food'])){
echo 'Orange was checked!';
}
Remember to check the array is set first, such as:
if(isset($_POST['food']) && in_array(...
Let your html for your checkbox will be like
<input type="checkbox" name="check1">
Then after submitting your form you need to check like
if (isset($_POST['check1'])) {
// Checkbox is selected
} else {
// Alternate code
}
Assuming that check1 should be your checkbox name.And if your form submitting method is GET then you need to check with $_GET variables like
if (isset($_GET['check1'])) {
// Checkbox is selected
}
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.
HTML Code: (for Add Page)
<input name="status" type="checkbox" value="1" checked>
Hint: remove checked if you want to show it as unchecked by default
HTML Code: (for Edit Page)
<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
PHP Code: (use for Add/Edit pages)
$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.
To check if a checkbox is checked use empty()
When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.
Check if checkbox is checked with empty as followed:
//Check if checkbox is checked
if(!empty($_POST['checkbox'])){
#Checkbox selected code
} else {
#Checkbox not selected code
}
You can check the corresponding value as being set and non-empty in either the $_POST or $_GET array depending on your form's action.
i.e.: With a POST form using a name of "test" (i.e.: <input type="checkbox" name="test"> , you'd use:
if(isset($_POST['test']) {
// The checkbox was enabled...
}
You can do it with the short if:
$check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
or with the new PHP7 Null coalescing operator
$check_value = $_POST['my_checkbox_name'] ?? 0;
Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set
Example:
if(isset($_POST["testvariabel"]))
{
echo "testvariabel has been set!";
}
Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:
//EMPTY ALL VALUES TO 0
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
if(!empty($_POST['check_menus'])) {
foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
$queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
$stmtMU = $db->prepare($queryMU);
$stmtMU->execute();
} catch(PDOException $e) {
$msg = 'Error: ' . $e->getMessage();}
}
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />
....
The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.
Example is PHP but applies for everything.
Have fun :)
$is_checked = isset($_POST['your_checkbox_name']) &&
$_POST['your_checkbox_name'] == 'on';
Short circuit evaluation will take care so that you don't access your_checkbox_name when it was not submitted.
A minimalistic boolean check with switch position retaining
<?php
$checked = ($_POST['foo'] == ' checked');
?>
<input type="checkbox" name="foo" value=" checked"<?=$_POST['foo']?>>
<?php
if (isset($_POST['add'])) {
$nama = $_POST['name'];
$subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";
echo "Name: {$nama} <br />";
echo "Subscribe: {$subscribe}";
echo "<hr />";
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="text" name="name" /> <br />
<input type="checkbox" name="subscribe" value="news" /> News <br />
<input type="submit" name="add" value="Save" />
</form>
<form>
<input type="check" id=chk1 value="1">
<input type="check" id=chk2 value="1">
<input type="check" id=chk3 value="1">
</form>
when you check on chk2 you can see values as:
<?php
foreach($_POST as $key=>$value)
{
if(isset($key))
$$key=strip_tags($value);
}
insert into table (chk1,chk2,chk3) values ('','1','');
?>
in BS3 you can put
<?php
$checked="hola";
$exenta = $datosOrdenCompra[0]['exenta'];
var_dump($datosOrdenCompra[0]['exenta']);
if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){
$checked="on";
}else{
$checked="off";
}
?>
<input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>
Please Note the usage of isset($datosOrdenCompra[0]['exenta'])
Wordpress have the checked() function.
Reference: https://developer.wordpress.org/reference/functions/checked/
checked( mixed $checked, mixed $current = true, bool $echo = true )
Description
Compares the first two arguments and if identical marks as checked
Parameters
$checked
(mixed) (Required) One of the values to compare
$current
(mixed) (Optional) (true) The other value to compare if not just true
Default value: true
$echo
(bool) (Optional) Whether to echo or just return the string
Default value: true
Return #Return
(string) html attribute or empty string
i have fixed it into a PHP form with a checkbox
$categories = get_terms( ['taxonomy' => 'product_cat', 'hide_empty' => false] );
foreach ($categories as $categorie) {
echo "<input type="checkbox" value="$categorie->term_taxonomy_id" name="catselected[]"> $categorie->slug";
}
This way i add it to the Woocommerce tabel.
wp_set_post_terms( $product_id, $_POST['catselected'], 'product_cat' );
filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)
<?php
if(isset($_POST['nameCheckbox'])){
$_SESSION['fr_nameCheckbox'] = true;
}
?>
<input type="checkbox" name="nameCheckbox"
<?php
if(isset($_SESSION['fr_nameCheckbox'])){
echo 'checked';
unset($_SESSION['fr_nameCheckbox']);
}
?>
you should give name to your input .
then which box is clicked you will receive 'on' in your choose method
Array
(
[shch] => on
[foch] => on
[ins_id] => #
[ins_start] => شروع گفتگو
[ins_time] => ما معمولاً در چند دقیقه پاسخ میدهیم
[ins_sound] => https://.../media/sounds/ding-sound-effect_2.mp3
[ins_message] => سلام % به کمک نیاز دارید؟
[clickgen] =>
)
i have two checked box in my form name with 'shch' and 'foch'