checkboxes in php form doesn't work - php

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,,,

Related

Codeigniter Getting the value of a checkbox

I want to get the value of a checkbox once it checked.
From my code
$vat_checkbox = $this->input->post('vat_checkbox');
print_r($vat_checkbox);
die();
it display "on". I will use it for validation. What would be the proper way without using javascript?
When checkbox is checked you will get value as on else you will not get that tag also. so You can do something like this.
$post['vat_checkbox'] = $this->input->post('vat_checkbox');
if(isset($post['vat_checkbox']) && $post['vat_checkbox'] == 'on') {
$post['vat_checkbox'] = 1;
} else {
$post['vat_checkbox'] = 0;
}
Here $post['vat_checkbox'] you can use for operation
Just add value attribute in input tag if you dont want to do with jquery
<form action="test.php" method="POST">
<input type="checkbox" name="vat_checkbox_1" value="1" checked>
<input type="checkbox" name="vat_checkbox_2" checked>
<input type="submit" name="submit" value="SUBMIT">
</form>
If you added value then it will give you value from value attribute else "on"
Output:
Array
(
[vat_checkbox_1] => 1
[vat_checkbox_2] => on
[submit] => SUBMIT
)
Here, In Controller you can directly use your checkbox data without any manipulation.

Trying to set default checkbox value if not checked

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...

Storing checkbox values in session and then reselecting them through session

I am simply trying to pass my checkbox values through a session variable for use if the user goes back at some point. After going to my first page and POSTING, I want these selections stored in a SESSION variable. I've had no luck so far in figuring this one out. My code is below.
Here is my html of my checkboxes. I have about 15 checkboxes with the same name as below. I take all those checkboxes and break them down in another script for insertion into a database.
<input type='checkbox' name='list[]' id='product' value='Product'></input>
Here I am setting my variable with the POST of the checkboxes.
$checkboxes = $_POST['list'];
$_SESSION['list'] = $checkboxes;
How can I pass these checkbox selections into and out of a session variable for selecting elements on a previous page?
Change:
<input type='checkbox' name='list[]' id='product' value='Product'></input>
To
<input type='checkbox' name='list[0]' id='product' value='Product'></input>
<input type='checkbox' name='list[1]' id='product' value='Product'></input>
etc.
And use foreach:
Okay so. We know that in $_SESSION['list'] we have only checked ones!
foreach ($_SESSION['list'] as $key => $value)
{
echo '<input type="checkbox" name="list['$key']" value="'.$value.'" checked="checked >';
}
Just thought I share my code / solution for storing the html form checkbox value in a session. My search did not get me to cover all scenarios that I needed.
My scenario includes that I pass a default state for checked or not checked.
HTML Form Code:
<input type="hidden" name="product[]" value = 0>
<input name="product[]" type="checkbox" value = 1 <?php echo (($productvalue == 1) ? 'checked' : '')?>>
PHP Form processing code:
$productvalue = ((isset($_POST['product'])) ? array_sum((array)$_POST['product']) : ((isset($_SESSION['productsession'])) ? $_SESSION['productsession'] : 0));
$_SESSION['productsession'] = $productvalue;

how to get value of checked with checkbox row in php?

I am trying to get values of rows which are checked using checkbox. So when I submit the form I want values of selected rows but I am not able to figure it out how to get it. Can anybody help me or guide me?
<?php
if(isset($_POST['invite'])){
// what should I write here to get value of hidden fields name and email which was selected
}
?>
<!doctype>
<html><head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
// performing select all /deselect all checkbox operation
<SCRIPT language="javascript">
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head><body>
<div class = 'middle' style = 'width : 700px;background-color:beige'>
// creating grid view
<form type="post" name ="contacts">
<span><input type="checkbox" id="selectall"/></span>
<div class = 'middle row'>NAME</div>
<div class = 'middle row'>E-MAIL</div>
<div class='line'></div>
<div class='line'></div>
<?php foreach($email as $e){
echo "<div>
<span><input type='checkbox' class='case' name='case'/></span>
<div class='row'>".$e['name']."
<input name='cname[]' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail[]' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
}
echo"<input type='submit' name='invite' value='invite'>
</form></div></body></html>";
}?>
After submitting the form, the value of a checked checkbox appears in the $_POST array like any other form fields. In your case, you have multiple checkboxes named case. None of those has a specific value assigned, so $_POST['case'] will equal on if any checkbox is checked, so this won't help you at all.
Change the name of the checkbox to case[] and assign a unique value to each, and $_POST['case'] will contain an array of the values of all checked checkboxes after submit. For instance, you could repeat the values of the hidden fields in the value attribute of your checkbox.
I wrote a small php script that should help you to understand, how checkboxes work with php. Just run it, play with the checkboxes and have a look at the $_POST array afterwards.
<!doctype html>
<html>
<body>
<form method="post">
<input type="checkbox" name="test[]" value="0"/>
<input type="checkbox" name="test[]" value="1"/>
<input type="checkbox" name="test[]" value="2"/>
<input type="checkbox" name="test[]" value="3"/>
<input type="checkbox" name="test[]" value="4"/>
<input type="submit"/>
</form>
<pre><?php var_dump($_POST); ?></pre>
</body>
</html>
If you want to keep your hidden fields and don't want to repeat their values in the checkbox element, you can also use the array key of their arrays as checkbox value:
<?php
$i = 0;
foreach($email as $e) {
echo "<div>
<span><input type='checkbox' class='case' name='case[]' value='".$i."'/></span>
<div class='row'>".$e['name']."
<input name='cname['".$i."']' type='hidden' value =".$e['name']."></div>
<div class='row'>".$e['email']."
<input name='cemail['".$i."']' type='hidden' value =".$e['email']."></div>
</div><div class='line'></div>";
$i++;
}
Now, if $_POST['case']contains the values 2, 4 and 8 for instance, the emails you are looking for, are in $_POST['cemail'][2], $_POST['cemail'][4] and $_POST['cemail'][8]. Same applies for $_POST['cname'], of course.
First of all, there's a mistake in an argument of form tag:
<form type="post"
This should read
<form method="post"
Then, since you store name and e-mail in the inputs named cname[] and cemail[], they will be passed respectively in $_POST['cname'] and $_POST['cemail'] variables. Note that you named them in a way they will be passed as arrays, so actually, $_POST['cname'] is an array - it contains a key-value pair of 0 and the value attribute of the input control. So actually, your name and e-mail will be in $_POST['cname'][0] and $_POST['cemail'][0] variables.
Please analyse and also read Dealing with Forms section of PHP manual.

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