Trying to set default checkbox value if not checked - php

Basically I can get the value that applies to when the box is ticked (= 1), but I can't get it to send the default value of 0 when not checked.
<input type="checkbox" name="post_friend" value="1">
I've searched around and someone suggested setting a hidden checkbox, but it's not working for me.
<input type="hidden" name="post_friend" value="0">

Could you not do something like this?
$checkbox = isset($_POST['post_friend']) ? $_POST['post_friend'] : 0 ;
So if the checkbox is checked, variable is 1. If not, variable assigned value of 0

The original method which was given by the OP should work, however, the value may very well be different.
For example,
<input type="checkbox" name="post_friend" value="1">
<input type="hidden" name="post_friend" value="0">
In this case ["post_friend"] = 0.
However, in this example:
<input type="checkbox" checked="checked" name="post_friend" value="1">
<input type="hidden" name="post_friend" value="0">
Most browsers will send ["post_friend"] = "1,0".
Multiple values to the same property will usually be concatenated in the http request.
For this you can use String.Contains to find the 1.
However, here, you should really assess whether your input should be a checkbox, or more suitably, radio input.

Try something like below
<div class="col-xs-5 drinkingLeft">
<input type="checkbox" name="beer" id="beer"class="require-one col-xs-1" value="0"/>
<input id='beerHidden' type='hidden' value='0' name='beer'>
<label for="beer" class="col-xs-10">Beer </label>
</div>
$('#beer').on('change', function () {
this.value = this.checked ? 1 : 0;
}).change();
$("#submit").click(function () {
if(document.getElementById("beer").checked){
document.getElementById('beerHidden').disabled = true;
}
});

HTML
<input type="checkbox" id="chkbox1">
Jquery
if( $("#chkbox1").is(':checked')){
value = "True";
}else{
value= "False";
}

the only possible solution is :
<?php
// if data is posted, set value to 1, else to 0
$check_0 = isset($_POST['check'][0]) ? 1 : 0;
$check_1 = isset($_POST['check'][1]) ? 1 : 0;
?>
If you want to check info on the same page then use JS and check NULL values...

Related

How to get checkbox value if it is not checked? [duplicate]

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'

checkboxes in php form doesn't work

How can I use the conditional OR in a form with isset?
I have this but it does not work.
FORM HTML:
...
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
...
and the PHP
$cargas=array($_POST['carga1'],$_POST['carga2'],$_POST['carga3'],
$_POST['carga4'],$_POST['carga5'],$_POST['carga6'],
$_POST['carga7'],$_POST['carga8'],$_POST['carga9'],
$_POST['carga10'],$_POST['carga11'],$_POST['carga12'],
$_POST['carga13'],$_POST['carga14'],$_POST['carga15'],
$_POST['carga16'],$_POST['carga17'],$_POST['carga18']);
if(isset($cargas[0]) ││ isset ($cargas[1])){
$cargas[0]=5.62;
$cargas[1]=4.5;
echo "$cargas[0]<br>";
echo "$cargas[1]<br>";
}
i expect that this works but is not.
Only checked checkbox is posted to the server.You have to change your condition using pregmatch and work accordingly.
$postData = $_POST;
foreach ($postData as $key => $value) {
$match = preg_match('|cargas(\d+)|', $key, $matches);
if ($match) {
$index = $matches[1];
if($index == 0 || $index == 1){
// do your stuff which you would have done in case of $cargas[0] ,$cargas[1]
}
}
}
I think array is not Suitable way to do this try following
try this
<input type="checkbox" name="carga1">
<input type="checkbox" name="carga2">
.....................................
<input type="submit" name="submit">
<?php
if(isset($_POST['submit'])){
//
$category1=$_POST['carga1'];
$category2=$_POST['carga2'];
$category3=$_POST['carga3'];
if(isset($category1) ││ isset ($category2)){
$category1=5.62;
$category2=4.5;
echo "$category1<br>";
echo "$category2<br>";
}
}
?>
only the checked checkboxes get posted. so it needs slightly different appraoch.
You can acheive it like this-
put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' id='testName' value='0' name='carga1'>
<input type='checkbox' id='testNameHidden' value='1' name='carga1'>
</form>
Before submitting the form , disabled the hidden field based on the checked condition.
<script>
if(document.getElementById("testName").checked){
document.getElementById('testNameHidden').disabled = true;
}
</script>
I personally think its the easiest approach for this.
ok, check boxes in html works as follows,
<input type="checkbox" name="carga1" value="1">
<input type="checkbox" name="carga2" value="123">
in php,
if the check box is in checked state during the submission, you will get
isset($_POST['carga1']) as true, else the form element would not be available in post data, hence false.
and in cheked state you will get value for
$_POST['carga1'] as 1 and
$_POST['carga2'] as 123
and if you want to group the check boxes in form you can use a single name for multiple check boxes and different values,
<input type="checkbox" name="carga[]" value="1">
<input type="checkbox" name="carga[]" value="2">
<input type="checkbox" name="carga[]" value="3">
<input type="checkbox" name="carga[]" value="4">
and in php you will get an array of selected values of the check boxes
$arr=$_POST['carga'];
and you can use foreach to iterate through the values,,,

How to access a checkbox with a PHP script via POST when there are multiple checkboxes in the same form

I have a form for editing notifications that looks like:
<form action='edit.php' method = 'post'>
<b> Username</b>:<br/> <input type='text' name ='username' value ="<?=$username?>" /><br/>
<input type = "checkbox" id="r_notif" name="r_notif" checked="yes" /> Response Notifications<br/>
<input type = "checkbox" id="c_notif" name="c_notif" checked="yes" /> Comment Notifications<br/>
<input type ='submit' value = 'SEND' />
</form>
In edit.php, I want to set the value of $r_notif to 1 if checked ="yes" for the input with name resp_notif. Similarly, I want to set the value of $c_notif to 1 if checked = "yes" for input c_notif. I set them to zero otherwise in each case.
Problem is I only know how to access $_POST['name_of_field'] and don't know how to access the checked value...How can this be done (in PHP or otherwise)
Thanks!
It's a good idea to add value fields to your markup, that way you can be sure of what the contents of the POST will be, and it will not vary between browsers;
<input type = "checkbox" id="r_notif" name="r_notif" checked="yes" value="yes" />
<input type = "checkbox" id="c_notif" name="r_notif" checked="yes" value="yes" />
Then in your php;
if($_POST['r_notif'] == 'yes') $r_notif = 1;
else $r_notif = 0;
if($_POST['c_notif'] == 'yes') $c_notif = 1;
else $c_notif = 0;
if(isset($_POST['name_of_field']))
Try
var_dump($_POST['r_notif']);
var_dump($_POST['c_notif']);
and different variations of checking/not checking your checkboxes. You should be able to answer your own question (literally, this is much encouraged on stackoverflow!) pretty soon.

How to read if a checkbox is checked in PHP?

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'

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