Checkbox not showing as checked - php

The issue is I have a page with the following checboxes listed for a particular question.When I select one of the boxes and go to the next page and comeback then i find,none of the checkboxes appear to be checked.I have checked it on the back end and i was able to see that the checkboxes were indeed checked,but i was not able to view them as checked.I am not able to figure out as to why they dont appear to be checked.Any help regarding this would be appreciated.Thanks in Advance. The following is the code which i have in that page.
<td>
<input type="checkbox" name="test_na" value="N/A" <?=$test_na?> id="test_na">
<label for="test_na">NA</label>
</td>
<td>
<input type="checkbox" name="test_y" value="Y" <?=$test_y?> id="test_y">
<label for="test_y">Yes</label>
</td>
<td>
<input type="checkbox" name="test_n" value="N" <?=$test_n?> id="test_n">
<label for="test_n">No</label>
</td>

Test the value of the checkoxes and echo checked if value matches.
<td>
<input type="checkbox" name="test_na" value="N/A" <?php echo (isset($test_na) && $test_na == 'N/A' ? 'checked' : ''); ?> id="test_na">
<label for="test_na">NA</label>
</td>
<td>
<input type="checkbox" name="test_y" value="Y" <?php echo (isset($test_y) && $test_y == 'Y' ? 'checked' : ''); ?> id="test_y">
<label for="test_y">Yes</label>
</td>
<td>
<input type="checkbox" name="test_n" value="N" <?php echo (isset($test_n) && $test_n == 'N' ? 'checked' : ''); ?> id="test_n">
<label for="test_n">No</label>
</td>

See page source. What in your variables? It should be checked="checked" or checked="yes" or checked="1"

Related

Submit an array checkbox although it's not checked

I have some multi-value inputs and there are some checkboxes among them. When I submit the form, if a checkbox is not checked, it shifts up the rest of the data and misplaces inputs in other rows.
For example, if those two checkboxes are not checked in the middle, when I use a foreach loop, it uses the fourth hazardous input in the second row and data is misplaced in database.
Here is my code:
<td>
<input type="text" name="description_of_goods_fa[]"
class="form-control">
</td>
<td>
<input type="text" name="hs_code[]" required
title="HS Code needs to be a 8 digit number"
class="form-control" pattern="[0-9]{8}">
</td>
<td>
<input type="checkbox" name="stackable[]" class="form-control"
value="1" checked>
</td>
<td>
<input type="checkbox" name="hazardous[]" class="form-control"
onchange="check_hazardous(this);" value="1">
</td>
<td>
<input type="number" name="un[]" min="0" max="9999" step="1"
class="form-control" readonly>
</td>
<td>
<input type="number" name="imco_class[]" min="1" max="9.9"
step="0.1" class="form-control" readonly>
</td>
And I use a foreach loop to go through $_POST in php:
foreach($_POST['hs_code'] as $key => $hs_code)
{
$description_of_goods_en = $mysqli->real_escape_string($_POST['description_of_goods_en'][$key]);
$description_of_goods_fa = $mysqli->real_escape_string($_POST['description_of_goods_fa'][$key]);
$hs_code = $mysqli->real_escape_string($_POST['hs_code'][$key]);
$hs_code = $mysqli->real_escape_string($_POST['hs_code'][$key]);
$stackable = (isset($_POST['stackable']) ? '1' : '0');
$hazardous = (isset($_POST['hazardous'][$key]) ? '1' : '0');
$un = (isset($_POST['un'][$key]) ? $mysqli->real_escape_string($_POST['un'][$key]) : "");
$imco_class = (isset($_POST['imco_class'][$key]) ? $mysqli->real_escape_string($_POST['imco_class'][$key]) : "");
$no_of_unit = $mysqli->real_escape_string($_POST['no_of_unit'][$key]);
$unit_price = $mysqli->real_escape_string($_POST['unit_price'][$key]);
$total_price = $mysqli->real_escape_string($_POST['total_price'][$key]);
$no_of_packages = $mysqli->real_escape_string($_POST['no_of_packages'][$key]);
$kind_of_packages = $mysqli->real_escape_string($_POST['kind_of_packages'][$key]);
$pkg_length = $mysqli->real_escape_string($_POST['pkg_length'][$key]);
$pkg_width = $mysqli->real_escape_string($_POST['pkg_width'][$key]);
$pkg_height = $mysqli->real_escape_string($_POST['pkg_height'][$key]);
$pkg_volume = $mysqli->real_escape_string($_POST['pkg_volume'][$key]);
$total_volume = $mysqli->real_escape_string($_POST['total_volume'][$key]);
$pkg_net_weight = $mysqli->real_escape_string($_POST['pkg_net_weight'][$key]);
$pkg_gross_weight = $mysqli->real_escape_string($_POST['pkg_gross_weight'][$key]);
$total_net_weight = $mysqli->real_escape_string($_POST['total_net_weight'][$key]);
$total_gross_weight = $mysqli->real_escape_string($_POST['total_gross_weight'][$key]);
$chargeable_weight = (isset($_POST['chargeable_weight'][$key]) ? $mysqli->real_escape_string($_POST['chargeable_weight'][$key]) : "");
if($hs_code != '' || $no_of_packages != '' || $description_of_goods_en != '' || $volume != '')
{
$sql = "
INSERT INTO `inquery_cargo` SET
`id_inquery`='$id_inquiry',
`description_of_goods_en`='$description_of_goods_en',
`description_of_goods_fa`='$description_of_goods_fa',
`hs_code`='$hs_code',
`stackable`='$stackable',
`hazardous`='$hazardous',
`un`='$un',
`imco_class`='$imco_class',
`no_of_unit`='$no_of_unit',
`unit_price`='$unit_price',
`total_price` = '$total_price',
`no_of_packages`='$no_of_packages',
`kind_of_packages`='$kind_of_packages',
`pkg_length`='$pkg_length',
`pkg_width`='$pkg_width',
`pkg_height`='$pkg_height',
`pkg_volume`='$pkg_volume',
`total_volume`='$total_volume',
`pkg_net_weight`='$pkg_net_weight',
`pkg_gross_weight`='$pkg_gross_weight',
`total_net_weight`='$total_net_weight',
`total_gross_weight`='$total_gross_weight',
`chargeable_weight`='$chargeable_weight'
";
$res = $mysqli->query($sql);
if(!$res)
{
$text = "An error occurred during the process.";
$error = true;
}
}
}
How can I submit those checkboxes that are not checked?
There is at least two solutions
1) You should pass an index of row to form field name for each row. For example
<tr>
...
<input type="text" name="description_of_goods_fa[1]"
class="form-control">
...
</tr>
<tr>
...
<input type="text" name="description_of_goods_fa[2]"
class="form-control">
...
</tr>
So in the PHP code you can check in the loop for the existence of index as
$hazardous = isset($_POST['hazardous'][$index]) ? $_POST['hazardous'][$index] : null;
2) You can place a hidden input with name hazardous in addition to checkbox
<input type="checkbox" class="form-control hazardous-checkbox"
onclick="changeHazardousInput(this)" value="1">
<input type="hidden" name="hazardous[]"
onchange="check_hazardous(this);">
So then you just need to write a 'changeHazardousInput' function that changes sibling hidden input's value
Example of the changeHazardousInput function:
function changeHazardousInput(checkbox) {
checkbox.nextElementSibling.value = checkbox.checked ? checkbox.value : '';
}
There is a good way to solve your task and also to improve code readability. Just change the HTML structure to root both checkboxes under same row number. You still not receive unticked checkboxes, but since the data is grouped under line number it isn't a problem anymore.
<tr>
<td>
<input type="text" name="line[1][description_of_goods_fa]" class="form-control">
</td>
<td>
<input type="text" name="line[1][hs_code]">
</td>
<td>
<input type="checkbox" name="line[1][stackable]" value="1" checked>
</td>
<td>
<input type="checkbox" name="line[1][hazardous]" onchange="check_hazardous(this);" value="1">
</td>
</tr>
<tr>
<td>
<input type="text" name="line[2][description_of_goods_fa]" class="form-control">
</td>
<td>
<input type="text" name="line[2][hs_code]">
</td>
<td>
<input type="checkbox" name="line[2][stackable]" value="1" checked>
</td>
<td>
<input type="checkbox" name="line[2][hazardous]" onchange="check_hazardous(this);" value="1">
</td>
</tr>
Please see below code for html. for loop value of i will be dynamic or your definedd
<?php for($i=0;$i<5;$i++):?>
<tr>
<td>
<input type="checkbox" name="stackable[]" class="form-control"
value="1" checked>
</td>
<td>
<input type="checkbox" name="hazardous[]" class="form-control"
value="1">
</td>
</tr>
<?php endfor;?>
<input type="hidden" name="row" value="<?php echo $i?>">
and see below code for php file where you submit data
$row=$_POST['row'];
$stack=$_POST["stackable"];
$hazar=$_POST["hazardous"];
for($i=0;$i<$row;$i++){
$stackable=(isset($stack[$i]))?1:0;
$hazardous=(isset($hazar[$i]))?1:0;
}
Its will be help full for you.

remember checkbox value if its checked array name in a form php

lets say we have this:
echo '<form method="post">
<div class="form-group">
<table class="table table-bordered table-hover table-striped" style="width:auto">
<tr>
<td><label for="array">ARRAY_NAME</label></td>
<td>
<input type="checkbox" name="array[]" value="1" /> option1<br />
<input type="checkbox" name="array[]" value="2" /> option2
</td>
</tr>
<tr>
<td><label for="array2">ARRAY_NAME2</label></td>
<td>
<input type="checkbox" name="array2[]" value="1" /> option1<br />
<input type="checkbox" name="array2[]" value="2" /> option2
</td>
</tr>
<tr>
<td><label for="array3">ARRAY_NAME3</label></td>
<td>
<input type="checkbox" name="array3[]" value="1" /> option1<br />
<input type="checkbox" name="array3[]" value="2" /> option2
</td>
</tr>
</table>
</div>
<button type="submit" name="submit" class="btn btn-success">Submit</button>
</form>';
I tried to implement this code: <?php echo (isset($_POST['array1[0]']) && $_POST['array1[0]'] == 1) ? "checked='checked'" : "" ?>
but it didn't work! It only works if you have name="array1" and name="array2". this way I'm thinking I can save multiple data in a parent array saved! Like this form[array1[],array2[],array3[]].
Can someone give me a solution because I'm stuck! Thanks in advance guys!!
You are trying to access the values incorrectly.
You can access a array posted like this:
echo $_POST['array1'][0];
php.net/$_POST See the first comment.
When you put square brackets in the name of form control, PHP will inflate that set of elements with similar names into an array.
You need to access:
$_POST['array1'][0]
not
$_POST['array1[0]'] // This is incorrect
(You also need to match the actual name of your control: Your HTML has array, array2 and array3 but not array1)

keep radio button values and set default checked

I have a form with a radio button group. I want to set 'checked' as default the second radio button, and also keep the value after submitting form if user clicks on the first one.
Note that I'm using the <span class="custom-radiobutton"></span> for style the radiobuttons, with a lower z-index than the real <input type="radio", which has opacity:0.
This is a snippet of my code:
<div class="group-wrapper">
<div class="radiobutton-wrapper boolean">
<span class="custom-radiobutton"></span>
<input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if ((isset($_POST['hosting'])) && ((isset($_POST['hosting'])) == 1)) {echo 'checked="checked"';}; ?> />
<label for="hosting-1">Sí</span>
</div>
<div class="radiobutton-wrapper boolean">
<span class="custom-radiobutton"></span>
<input type="radio" id="hosting-2" name="hosting[]" value="0" class="w100" <?php if ((!isset($_POST['hosting'])) || ((isset($_POST['hosting'])) == 0)) {echo 'checked="checked"';}; ?> />
<label for="hosting-2">No</label>
</div>
</div>
Additional info:
I'm using HTML5.
I'm validating the form with PHP (I want to keep this, even if I know maybe is better jQuery+PHP validation).
I have noticed that I need two clicks to select the first radio button. This only occurs from original state. After this, It works with one click, as expected.
I'm expending a lot of hours trying to figure out what's wrong, so any help will be very appreciated.
Cheers,
<input type="radio" id="hosting-1" name="hosting[]" class="w100" checked="checked" /> 1
try this in your code.
for example:
<tr>
<td><br><b>Reservation Handling : <span style="color:#FF0000">* </span></td>
<td><br><input type="radio" name="reservation" value="Delighted" required> Delighted<br></input></td>
</tr>
<tr>
<td> </td>
<td><input type="radio" name="reservation" checked="checked" value="Satisfied"> Satisfied</input></td>
</tr>
<tr>
<td> </td>
<td><input type="radio" name="reservation" value="Dissatisfied"> Dissatisfied</input></td>
</tr>
<tr>
<td> </td>
<td><input type="radio" name="reservation" value="N/A"> N/A</input></td>
</tr>
You have an error in your logic. You're using isset twice.
<input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if ((isset($_POST['hosting'])) && ((isset($_POST['hosting'])) == 1)) {echo 'checked="checked"';}; ?> />
You're essentially saying does isset equal 1, which in your case will always be true if $_POST['hosting'] has a value.
You should do this
<input type="radio" id="hosting-1" name="hosting[]" value="1" class="w100" <?php if (isset($_POST['hosting']) && $_POST['hosting'] == 1) {echo 'checked="checked"';} ?> />

Save radio button status php

Form table is introduced inside an echo and, for the texts fields, I use value=" ' .$_POST['name'] to set default value if form was already sent at least one time. It works properly.
However, how could I save radio buttons status when form was already sent? Thanks.
<tr>
<td colspan="2" align="left" valign="top"> <input type="radio" name="ambiente" value="si" />
Si
<input type="radio" name="ambiente" value="no" />
No</td>
</tr>
Simply:
<input type="radio" name="ambiente" value="si" <?php if ($_POST['ambiente'] == 'si') echo 'checked'; ?> /> Si
<input type="radio" name="ambiente" value="no" <?php if ($_POST['ambiente'] == 'no') echo 'checked'; ?> /> No
<?php
$checked = NULL;
if(isset($_POST['ambiente']) && $_POST['ambiente'] == 'no') {
$checked = 'checked="checked"';
}
?>
<input type="radio" name="ambiente" value="no" <?php echo $checked ?> />
Or this can be shown on one line:
<input type="radio" name="ambiente" value="no" <?php if (isset($_POST['ambiente']) && $_POST['ambiente'] == 'no') echo 'checked="checked"'; ?> />

How to set the value for Radio Buttons When edit?

I have a Gender Row with radio buttons male & female. when i register as first time the values of radio button will store in database. Now my question is if i edit that row again it want to come(that means checked) with that value as male/female. how to make it?
Note : Doing with php.
HTML Script :
<tr id="inside">
<td align="right" width="40%" id="side" >Gender</td>
<td width="3%"> </td>
<td align="left" width="50%">
<input type="radio" name="sex" value="Male" size="17">Male
<input type="radio" name="sex" value="Female" size="17">Female
</td>
</tr>
When you populate your fields, you can check for the value:
<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female
Assuming that the value you return from your database is in the variable $sex
The checked property will preselect the value that match
just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:
<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female
in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.
This is easier to read for me:
<input type="radio" name="rWF" id="rWF" value=1 <?php if ($WF == '1') {echo ' checked ';} ?> />Water Fall</label>
<input type="radio" name="rWF" id="rWF" value=0 <?php if ($WF == '0') {echo ' checked ';} ?> />nope</label>
Gender :<br>
<input type="radio" name="g" value="male" <?php echo ($g=='Male')?'checked':'' ?>>male <br>
<input type="radio" name="g" value="female"<?php echo ($g=='female')?'checked':'' ?>>female
<?php echo $errors['g'];?>
For those who might be in need for a solution in pug template engine and NodeJs back-end, you can use this:
If values are not boolean(IE: true or false), code below works fine:
input(type='radio' name='sex' value='male' checked=(dbResult.sex ==='male') || (dbResult.sex === 'newvalue') )
input(type='radio' name='sex' value='female' checked=(dbResult.sex ==='female) || (dbResult.sex === 'newvalue'))
If values are boolean(ie: true or false), use this instead:
input(type='radio' name='isInsurable' value='true' checked=singleModel.isInsurable || (singleModel.isInsurable === 'true') )
input(type='radio' name='isInsurable' value='false' checked=!singleModel.isInsurable || (singleModel.isInsurable === 'false'))
the reason for this || operator is to re-display new values if editing fails due to validation error and you have a logic to send back the new values to your front-end
If you are getting your values from a database table and creating radio buttons dynamically, here is the solution. The database records are fetched into an array in this example and used for creating radio buttons.
<?php foreach ($dbrecords as $item) : ?>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="paymentMethod" id="paymentMethod" value=<?php echo $item["Id"]; ?> <?php echo ($paymentMethod == $item["Id"]) ? 'checked' : '' ?>><?php echo $item["Name"]; ?>
</div>
<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>

Categories