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.
Related
im kinda trying to get into programming in general and was wondering how to uncheck / check with updating the array-
like as soon as someone checks a 2nd checkbox it should uncheck the first option and update the search (w the new data)- im a mere beginner and kinda lost rn so would appreciate any form of help
<form action="index.php" id="form1" name="form1" method="get">
<?php $i = 0; foreach ($row_page_nav_kategorie as $row_page_nav_kategorie) { ?>
<label class="checkbox-container">
<input <?php if (strpos($url,$row_page_nav_kategorie['typ']) == true) {echo 'checked="checked"';}?>
type="checkbox"
class="checkmark"
name="hotelKategorie[]"
id="ckb5"
value="<?php echo $row_page_nav_kategorie['typ']; ?>"
onclick="kategorie(<?php echo $i ?>);"
onchange="submit()"/>
<?php echo $row_page_nav_kategorie['typ']; $i++;?>
</label>
<?php } ?>
</form>
You should use radio buttons, but if you want to overwrite checkbox functionality below code will take care of it, I have added a common class on your inputs:
function checkboxClick(obj) {
var cbs = document.getElementsByClassName("checkkbox-option");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo
First of all welcome to the community!
As for your question, there is multiple ways to handle this, one of wich is as followed:
In HTML there's an attribute called radio wich you can add to your input by using type='radio'. In a set of radio buttons, only one can be checked at any time. If you then want to immedietely submit your form, you can use something like onChange='this.form.submit()'. This will submit your form when the value is changed, such as pressing on a different radio button.
Something to keep note of is that the attribute onChange is case sensitive as far as i'm aware. You were heading in the right direction with onchange="submit(), but your code doesn't know what to submit. this.form.submit() will submit the form that the element is in.
Use Radio Buttons or use JavaScript on your page to dynamically uncheck other checkboxes when you click on one.
If you want to dynamically update the page content with the new search results you should also look into AJAX which basically means you will call PHP functions from JavaScript code and those will return JSON arrays that you can exploit to modify your page's DOM.
Try THIS
HTML:
<label><input type="checkbox" name="check1" class="checkbox" /> CheckBox1</label>
<label><input type="checkbox" name="check2" class="checkbox" /> CheckBox2</label>
<label><input type="checkbox" name="check3" class="checkbox" /> CheckBox3</label>
<label><input type="checkbox" name="check4" class="checkbox" /> CheckBox4</label>
jQuery:
$(".checkbox").change(function() {
$(".checkbox").prop('checked', false);
$(this).prop('checked', true);
});
if you want to uncheck the selected checkbox
$(".checkbox").change(function() {
$(".checkbox").not(this).prop('checked', false);
});
hope this helps, thanks !!!
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,,,
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.
I have a form with multiple checkboxes, which I want to put into an array. I go by the example provided here: http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
So I've prepared the files:
checkboxes.php:
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags[]" value="1" />1<br>
<input type="checkbox" name="tags[]" value="2" />2<br>
<input type="checkbox" name="tags[]" value="3" />3<br>
<input type="checkbox" name="tags[]" value="4" />4<br>
<input type="submit" value="Send" />
</form>
checkboxes2.php:
<?php
print_r($_POST["tags"]);
?>
Pretty simple...I realize I should only get the value of these textboxes and not if they have been selected or not. But I still get this error:
Undefined index: tags in checkboxes2.php on line 2
I have absolutely no idea what I did wrong here. I went by the example in the link above and did everything exactly the same (mainly copy/pasting and changing some parts like adding a submit button) but I don't get the output as shown in the example. I should at least get the values of each of these checkboxes, right?
What I want to do: I want to check the array of checkboxes, see which ones have been selected and add "yes" or "no" into a second array, like this:
<?php
$number1 = $_POST["tags"];
$number2 = array();
foreach($number1 as $number1_output)
{
if(isset($number1_output))
{
$number2[] = "yes";
}
else
{
$number2[] = "no";
}
}
print_r($number2);
?>
Well...it only half works. Only the checkboxes that have been selected are added to the array. So if I select "3" and "4" I get this:
Array ( [0] => yes [1] => yes )
What is the best way to deal with checkboxes in arrays and validating them?
Checkboxes which are not selected to do not send anything when the form submits. That means if NONE of those tags checkboxes are selected, there will be no tags attribute in the $_POST array.
As such, your code should be
<?
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['tags'])) {
print_r($_POST['tags']);
}
}
?>
The first line verifies that a POST has actually taken place, and the second line verifies that there's actually any data to dump out.
For the rest of your code, the isset is rather pointless... Since a checkbox is only present in the POST data if it was selected, there's no point in doing the isset() within your foreach loop - there'd be nothing to foreach on if there were no checkboxes, so by definition everything in the foreach will be isset() == true anyways.
As such, your foreach loop will only produce yes values, never a no.
A better workaround is to specify array keys within your form:
<input type="checkbox" name="tags[1]" value="1" />
<input type="checkbox" name="tags[2]" value="2" />
etc...
then have
<?php
if (b blah blah blah verify post stuff) {
for ($i = 1; $i <= $max_tags_allowed; $i++) {
if (isset($_POST['tags'][$i])) {
$message2[] = 'yes';
} else {
$message2[] = 'no';
}
}
}
Alternatively, if you want to have checkboxes that also send a value if they are not checked, you can add a Hidden input field before the checkbox:
<input type="hidden" name="tag[1]" value="off" />
<input type="checkbox" name="tag[1]" value="on />
Because the checkbox is only sent if it is set, but it overrides the hidden as it is later in the HTML, you will now always have tag[1] set with either 'off' or 'on' depending on whether or not the box was checked.
First create an array that holds "no" with all the possible keys, like this:
$no = array(0 => "no", 1 => "no"); // or array("no", "no");
Then you can get your desired array like that:
$checkValues = array_flip($_POST["tags"]) + $no;
This way the values in $_POST["tags"] will become keys, and the + operator merges the two array keeping the keys, also omitting values from the second array, if they are present in the first array. This way you can just check like this:
$fourthChecked = $checkValues[4] !== "no";
I thought its much simpler than the other answers. Good luck!
In your checkboxes.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>My form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" languaje="javascript">
$(document).ready(function() {
$('.checkbox').click(function(){
var values="";
$('.checkbox:checked').each(function(index) {
values+=$(this).val();
$('#tagsVal').val(values);
});
});
});
</script>
</head>
<body>
<form action="checkboxes2.php" method="post">
<input type="checkbox" name="tags1" value="1" class="checkbox"/>1<br><!--Notice the class="checkbox" attribute is important for the jquery function-->
<input type="checkbox" name="tags2" value="2" class="checkbox"/>2<br>
<input type="checkbox" name="tags3" value="3" class="checkbox"/>3<br>
<input type="checkbox" name="tags4" value="4" class="checkbox"/>4<br>
<input type="hidden" name="tagsVal" id="tagsVal" value="" />
<input type="submit" value="Send" />
</form>
</body>
</html>
So what you'll get in your $_POST['tagVal'] you'll get your values. If checkbox 1,3 and 4 are checked you'll get a string 134.
In your checkboxes2.php you'll only have to split the string into array if you need it.
$arr1 = str_split($_POST['tagVal']);
Regards
Luis
I'm trying to make a simple survey in php
I have a set of radio buttons on a page called sja.php that sends its to sjamail.php page
the problem is that when I go to get
$answer = $_POST['ans'];
I can't seen to do anything like
echo "$answer";
but if I were to throw some logic at it
like
if ($answer == "ans1") {
echo 'Correct';
}
else {
echo 'Incorrect';
}
It will display correct or incorrect (edit: The if/else works correctly and will display the correct answer )
so why is it I can't access the value of the radio button "ans" as a string?
http://www.markonsolutions.com/sja.php
print_r($_POST); will return Array ( [ans] => )
Perhaps the value is something other than text.
Try
var_dump($answer);
or
print_r($answer, TRUE);
Your page works correctly if you select any of the first 4 radio buttons (ans1/2/3/4). But the rest of the radio buttons next to all those images have blank values, which would explain why your posted value is empty if you selected any of those to test with.
You need to make sure that the field in HTML has...
<input type="radio" name="ans" value="ans1" />
<input type="radio" name="ans" value="ans2" />
Also make sure your form method is POST
I had a similar problem with the following:
<input name="03 - Gender" type="radio" value="Masculino"/>Male<br/>
<input name="03 - Gender" type="radio" value="Femenino" required="required"/>Female <br/>
<input type="hidden" name="03 - Gender" value=""/>
but when I removed the third input line (the hidden one) the problem desapeared.
Try this:
$answer = (string)$_POST["ans"];
echo $answer;
You must convert $_POST["ans"] to string.