Check Box selected attribute set regardless of value - php

Try this at home:
Write a form to display a list of checkboxes in PHP:
$checkboxes = array('one' => 1, 'two' => 2, 'three' => 3);
$html = "<html><body><form name=\"myForm\" action=\"this\" method=\"post\"><ul>Check Test";
foreach ($checkboxes as $id => $value)
{
$checkVal = (isset($_POST['check_test'][$id])) ? 'true' : 'false';
$checkList = "<li><input type=\"checkbox\" name=\"check_test[]\" id=\"$id\"
value =\"$value\" checked=\"$checkVal\" />$name = $value</li>\n";
}
$checkList .= "<input type=\"submit\" value=\"Submit\">";
echo $html.$checkList."</ul></body></html>";
You will find that no matter what you put into the $checkVal assignment, when you hit submit, your checkboxes will all be checked. My workaround is to expand the $checkVal variable to set the entire "checked='' status to either something or nothing. I'm just surprised that Firefox (rather, Iceweasel) is only looking to see if the attribute is set at all. Why even have it if whatever it's set to is irrelevant?
Look at the source html. The selected attribute will display whatever you put into the checkval variable. The DOM specification states:
checkboxObject.checked=true|false
Here is my output:
<ul><li><input type="checkbox" name="check_test[]" id="one"
value ="1" checked="false" />one= 1</li>
<li><input type="checkbox" name="check_test[]" id="two"
value ="2" checked="false" />two= 2</li>
<li><input type="checkbox" name="check_test[]" id="three"
value ="3" checked="false" />three= 3</li>
And lo and behold! Every box is checked. Contrary to what I've explicitly expressed in the html.

The false is ignored. If the check attribute exists the box is checked.
foreach ($checkboxes as $id => $value)
{
$checkVal = (isset($_POST['check_test'][$id])) ? 'checked="checked"' : '';
$checkList = "<li><input type=\"checkbox\" name=\"check_test[]\" id=\"$id\"
value =\"$value\" ".$checkVal." />$name = $value</li>\n;
}

Related

Show only the specific indexed array

How can I show only the specific index? For example, here's my UI.
As you can see in the picture I have 3 checkboxes and 3 textboxes with array value.
Let's say these are the name of the element.
<input type="checkbox" name="check[]">
<input type="text" name="textbox[]">
Then print the array:
$check = $_POST['check'];
$total_rec = $_POST['textbox'];
echo 'Check Array<br>';
print_r($check);
echo '<br<br><br><br>';
echo 'TextBox Array<br>';
print_r($textbox);
Result:
Check Array
Array ( [0] => 2 )
TextBox Array
Array ( [0] => [1] => 2 [2] => )
As you can see in textbox array all index showed, all I want is to show only the specific index with value and that is the 1 => 2 only.
use empty(), return true if contain value, example :
//iterate each $total_rec's member
foreach($total_rec as each){
//if $each not empty, do something
if(!empty($each)){
echo $each;
}
}
You are using $total_rec for post values of both checkbox and text. You can filter the array of text input like this:
$total_rec_text = $_POST['textbox'];
$total_rec_text = array_filter($total_rec_text, function($arr){
return !empty($arr) ? true : false;
});
You need to loop over $_POST array and check if checkbox is checked.
If checked, then only, get/print value.
Also, in HTML, you need to add specific counters to both checboxes and
textboxes.
As only checked checboxes get posted and texboxes get posted by
default.
<input type="checkbox" name="check[0]">
<input type="text" name="textbox[0]">
<input type="checkbox" name="check[1]">
<input type="text" name="textbox[1]">
<input type="checkbox" name="check[2]">
<input type="text" name="textbox[2]">
if (isset($_POST['check'])) {
foreach ($_POST['check'] as $idx => $value) {
echo "<br/>" . $_POST['check'][$idx] . ' ' . $_POST['textbox'][$idx];
}
}

Get a checkbox value even if it is unchecked when checkbox is an array name

I need to submit all my checkboxes on my page. I've got the following code to display the checkboxes:
foreach($categories as $category){
$cat_name = $category->name;
$cat_name = htmlspecialchars_decode($cat_name);
$list_name = $network_name.' '.$cat_name;
if (in_array($list_name, $list_names)) {
$checked = 'checked';
}else{
$checked = '';
}
$output .= '<input type="hidden" name="subscribe[]" value="0">';
$output .= '<input type="checkbox" name="subscribe[]" value="'.$list_name.'" '.$checked.'>';
$output .= $list_name;
$output .= '<br>';
}
Now I'm trying to process these with a foreach loop:
foreach($_POST['subscribe'] as $value){
echo "it has a value of".$value;
}
This will only show me the checkboxed boxes but I also want to get the value of the non-checked boxes. Is there a way to do this?
The problem that you have is with the naming. Each loop has 2 elements, both named subscribe[] so when posted you cannot see if the 'checked' value has overwritten the 'unchecked' value, as you just have an array of elements.
You need a way to link the 2 elements together so that they have the same name, and the value if checked will overwrite the value if not checked.
Try incrementing an integer inside your loop and using it in both elements, so that each 'loop' has a unique element name (rather than each input).
Try this modification:
$i = 1;
foreach($categories as $category){
$output .= '<input type="hidden" name="subscribe[$i]" value="0">';
$output .= '<input type="checkbox" name="subscribe[$i]" value="'.$list_name.'" '.$checked.'>';
$i++;
}

How can I combine values of checkboxes with values of text in php?

I'm new with PHP, and I'm making a html form which consist basically in two options: First, the client select a series of checkboxes (parts from an equipment) and then write the amounts of each selected checkbox...
<td><input id="11.11.015.0002" name="pecas[]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[]" size="7" type="text" /></td>
and in php:
if(isset($pecas))
{
$mensagem .= "Peças Selecionadas:<br /><br />";
}
else {
echo "<script>alert('Selecione as Peças Desejadas!'); location.href='http://www.lyuz.com.br/pecas/erro';</script>";
exit;
}
foreach ($pecas as $pecas_s) {
} $mensagem .= " - ".$pecas_s."<br />";
That gave me all the selected checkboxes (parts), now I'm trying to get only the input_text (amounts) associate with these selected checkboxes..
I'm stuck. Help.
Specify a key in the name of each element. Use a number and just make sure that pecas[1] corresponds to qntd[1]. Then when you loop over one of the arrays, the keys will be the same in the other array. For example:
<?php
$count = 0;
foreach($itemList as $item){
echo "<tr>\n";
echo " <td><input type='checkbox' id='{$item['id']}' name='pecas[{$count}]'></td>\n";
echo " <td><input type='test' id='{$item['id']}' name='qntd[{$count}]'></td>\n";
echo "</tr>\n";
$count++;
}
If there are 3 checkboxes and quantity boxes, and lets say the 1st and 3rd boxes are checked, but not the 2nd. Your post array will look like:
array(
'pecas'=> array(
0 => 'some value', //notice, no 1 key because the second checkbox was not checked.
2 => 'some other value'
),
'qntd' => array(
0 => 'some qntd',
1 => '' //1 was not checked, so nothing should have been entered in the second textbox.
2 => 'some other qntd'
)
);
The keys 0 (first checkbox) and 2 (third) will exist in the 'pecas' array and will correspond with keys 0 and 2 in the 'qntd' array. You can then loop over the data like:
//check that at least one checkbox was checked
if(!empty($_POST['pecas'])){
//loop over the checkboxes getting key ($k) and value ($v).
foreach($_POST['pecas'] as $k=>$v){
//display a message
echo "Pecas {$v} ({$k}) was checked with a qntd of {$_POST['qntd'][$k]}<br>";
}
}
Change
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
for($x = 0; $x < count($pecas); ++$x) {
$mensagem .= " - ".$pecas[$x]. ": " . $qntd[$x] . "<br />"; //Example
}
Since it appears that for every $pecas there is a $qntd, so you just need to get the index location of $pecas, and grab that same index location in $qntd
--
Let me add however that checkboxes only get passed IF they are checked, the input boxes will ALWAYS be passed. So you could have a disparity, where the indexes don't align! You might want to use some javascript to disable an input box if its checkbox is not selected.
Well, I manage to solve this with help of #Jonathan Kuhn with a little different approach.
In HTML form, I gave indexes in each element,
<td><input id="11.11.015.0002" name="pecas[1]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[1]" size="7" type="text" /></td>
And in PHP file, I replace
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
array('pecas'=> array(), 'qntd' => array());
if(!empty($_POST['pecas']))
{
foreach($_POST['pecas'] as $k=>$v)
{
$mensagem .= "- {$v} - QUANT.: {$_POST['qntd'][$k]}<br>";
}
}
And, finally, my mail returns value of each textbox when the checkbox is checked! \o/

php sum values of form check boxes when checked

I have a form in php that displays checkboxes. These checkboxes are associated with a numerical value populated from mysql. What I'm looking to do is add the values of each checkbox, but only if the box is checked.
The problem I am running into is no matter which boxes I have checked, the value from the first checkbox(es) are returned. For example, if there are 5 total checkboxes and I select the bottom 2, the returned sum is for the 2 top boxes not the bottom boxes. It seems my php code knows boxes are being checked, but just doesn't know which boxes are being checked.
Here is my form code
echo "<input type=\"hidden\" name=\"ID[]\" value=\"".$row['ID']."\" />";
echo "<tr><td> <input type=\"checkbox\" name=\"checked[]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[]\" value=\"".$row['amount']."\" />";
and here is my post
if('POST' == $_SERVER['REQUEST_METHOD']) {
$amt = 0;
$totamt = 0;
foreach($_POST['ID'] as $i => $id)
{
$id = mysql_real_escape_string($id);
$checked = mysql_real_escape_string($_POST['checked'][$i]);
$amt = mysql_real_escape_string($_POST['amount'][$i]);
if ($checked == "Y") {
$totamt = $totamt + $amt;
$amt = 0;
}
}
echo $totamt;
}
Thank you for your help.
The only checkboxes that are sent from the form are the ones that are checked, and the array indexes will start from 0 no matter which ones they are. So there's no correspondence between the indexes of the checkboxes and the indexes of the hidden fields. There are a few ways to deal with this.
One way is to put explicit indexes in the checkbox names:
echo "<tr><td> <input type=\"checkbox\" name=\"checked[".$row['ID']."]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[".$row['ID']."]\" value=\"".$row['amount']."\" />";
Then you can add up:
$totamt += $_POST['amount'][$_POST['checked'][$i]];
Another way is to put the amounts directly in the value of the checkboxes, instead of the useless Y value:
echo "<tr><td> <input type=\"checkbox\" name=\"checked[]\" value=\"".$row['amount']."\" /></td>";
Then you do:
$totamt += $_POST['checked'][$i];
A third way is to put explicit indexes in the names of all the fields, instead of letting PHP assign them when the form is submitted:
echo "<input type=\"hidden\" name=\"ID[".$i."]\" value=\"".$row['ID']."\" />";
echo "<tr><td> <input type=\"checkbox\" name=\"checked[".$i."]\" value=\"Y\"></td>";
echo "<input type=\"hidden\" name=\"amount[".$i."]\" value=\"".$row['amount']."\" />";
where $i is a variable that you increment as you're generating the form. This will make the indexes work the way your form code expects.
Looks like your hidden field and the actual checkbox have different names try putting them the same name
<input type='hidden" name='checkbox" value="no" />
<input type="checkbox" name="checkbox" value=$row['ID'] />
That way when you check the $_POST for checkbox name it will either show no or the id and you can determine what was checked
Basically the name of the hidden and checkbox should be the same
Another option to the ones already mentioned would to use JavaScript to do your adding and store the result in a hidden input field. You could use the onclick even to run a JS function that would add up the values (and you should definitely set it in the value of the checkbox instead of a hidden field). Then store your total into the hidden input field value. This would get passed in your POST along with the checkboxes. If you wanted to double check the amount, you could sum up the values of the checkboxes & compare to the hidden field.

Fill the checkboxes from an array in PHP

Everyone
My question is so clear I think:
I have an array of checkboxes in HTML
<input type="checkbox" name="gruplar[]" value="<?=$deptId?>">
It takes "value" values from database ID's e.g. 1,4,5
I can get these values in an array variable named $divided[]. For example 1,4,5 selected and the array is: $divided[0]=1,$divided[1]=4,$divided[2]=5,
When I need to update the record of checkbox list, I want to get this checkbox list selected with these array values.
Check the checkbox which has "value" of "1", "4" and "5" according to
the elements of the array.
How can I do that in HTML mixed PHP context?
<input type="checkbox" name="gruplar[]" value="<?=$deptId?>"<?=(in_array($deptId,$divided))?' checked="checked":''?> />
This checks if the value of the checkbox (as given by $deptId, which I'm assuming is what you meant as you're echoing it for the value attribute) is in the array $divided. If it is, it echos markup to make the checkbox checked when it is rendered by the browser.
<?php
$checked = array(1, 4, 5);
foreach ($all as $id) // $all is all checkboxes
{
sprintf('<input type="checkbox" name="gruplar[]" value="%d" %s>', $id, in_array($id, $checked) ? 'checked="checked"' : '');
}
?>
Also, it's better to build meta array like this
array(
//(int) id => (bool) checked
1 => true,
2 => false,
...
);
Then do:
foreach ($meta as $id => $checked)
{
sprintf('<input type="checkbox" name="gruplar[]" value="%d" %s>', $id, $checked ? 'checked="checked"' : '');
}
For Update ur Checkbox Field will display the PHP if else condition for comparing two variables for mapping
if(in_array($depid,$divided)){
$checked = "checked='checked'";
}else{
$checked = "";
}
<input type="checkbox" name="gruplar[]" value="<?=$deptId?>" <?=$checked; ?>/>

Categories