contact form group check box array - php

I have a contact form built with PHP and I had a radio option box (one click) and have changed it to a group check box, which means multiple boxes can be clicked.
However, only the last most click is sent through to my email and playing with the code has messed me up, I am not very clear with the php array code and multiple (({{
Here is the html code
<label><input type="checkbox" name="addon" value="NONE" <?php if (isset($_POST['addon']) && $_POST['addon'] == 'NONE') echo 'checked="checked"'; ?> tabindex="4" /> None <br /></label>
<label><input type="checkbox" name="addon" value="HKG" <?php if (isset($_POST['addon']) && $_POST['addon'] == 'HKG') echo 'checked="checked"'; ?> tabindex="5" /> Hong Kong <br /></label>
....
<label><input type="checkbox" name="addon" value="Other Start City" <?php if (isset($_POST['trip']) && $_POST['addon'] == 'Other Start City') echo 'checked="checked"'; ?> tabindex="4" /> Other</label>
and here is the php code I have at the moment, but this only gives one answer.
$Indhold .= "Tour Extension: ".$_POST['addon']."\n";
I tried changing it to an array (as I followed the tutorial http://www.html-form-guide.com/php-form/php-form-checkbox.html) , but then only array was printed on the email.
I also want to include validation on that combi box, if possible. So they can't choose NONE and HKG, and must click at least one.

PHP only populates $_POST/GET with arrays if the name ends in [] (or [index]).
Use name="addon[]"
Arrays aren't strings, so you can't just concatenate them. You can use implode to convert the members of an array into a single string. You could also use a for loop to deal with them one by one.

You just need to handle the $_POST['addon'] as an array (after naming your checkboxes "addon[]")
// make sure at least one checkbox is checked
if (isset($_POST['addon']))
{
foreach ($_POST['addon'] as $k => $v)
{
$Indhold .= "Tour Extension: {$v}\n";
}
}
Or as an alternative:
// make sure at least one checkbox is checked
if (isset($_POST['addon']))
{
$indhold .= 'Tour Extension: ' . implode(', ', $_POST['addon']) . "\n";
}

If in the form there are multiple input elements with a single name(i.e. not followed by '[]') only the latest of all those elements can be retrieved from the submitted form. So if you check more that one checkbox in a single group(i.e. the checkboxes having a single name which is not in the format 'name[]' but simple 'name') then you can get the last checked checkbox value from the form submit because all the previously checked values in the sigle group get overwritten. Hence you need to use an array for the group name to get all the checked checkbox values in the single group.
So always use the following syntax in case you have more than one checkbox in a single group:
<input type=checkbox name="check1[]" value="v1">v1
<input type=checkbox name="check1[]" value="v2">v2
<input type=checkbox name="check1[]" value="v3">v3
<input type=checkbox name="check1[]" value="v4">v4
But in case of a single checkbox use the following:
<input type=checkbox name="check2" value="v1">v1 //No need to append square bracket at the end of the assigned name.

Related

Get several checkboxes id's after submission

I have code similar to the following:
<input type="checkbox" name="visitProperty" value="1" id="visit-0">
<input type="checkbox" name="visitProperty" value="1" id="visit-1">
<input type="checkbox" name="visitProperty" value="1" id="visit-2">
...
Once the form is submitted I want to get checked checkboxes, so far I've been using
if (isset($_POST['visitProperty']) {..}
But to my understanding it only gets one checkbox? Where as I need to check all of them and see if they were checked, so inside the if statement I can create a loop that gets id's of all submitted checkboxes and then gets the number from id, to update a certain array.
<input type="checkbox" name="visitProperty[]" value="1" id="visit-0">
<input type="checkbox" name="visitProperty[]" value="2" id="visit-1">
<input type="checkbox" name="visitProperty[]" value="3" id="visit-2">
<?php
foreach($_POST['visitProperty'] as $check) {
echo $check . "<br>"; // for example
}
?>
NOTE: $_POST['visitProperty'] will hold checked checkbox values. You will access all the checkboxs as an array as following $_POST['visitProperty'][]
When you put in the name, you are declaring a variable. You need to declare it as an array, or each checkbox will bump out the last one. Add some empty square brackets to the name.
You would need or defined ID or a unique value, otherwise you will not be able to identify them on the server-side (the ID does not get sent in $_POST).
So in case of a unique, identifyable ID, you could do something like:
<input type="checkbox" name="visitProperty[<?php // echo some unique id from a database for example ?>]" value="1" id="visit-0">
The reason you would need the ID to be identifyable, is that unchecked checkboxes do not get sent to the server, so you might end up with an array of 2 if visitProperty is an array, but you would not know which 2.

How to validate multi-checkbox state?

I am using position absolute's validation engine for my form. I would like to check whether at least one checkbox from group is selected. In examples it is done by setting the same name attribute for group of checkboxes.
I cannot name checkboxes with the same name, because I am saving their state in database with following code:
$values = array(
'checkbox1' => null,
'checkbox2' => null
);
foreach (array_intersect_key($_POST, $values) as $key => $value) {
$values[$key] = mysql_real_escape_string($value);
}
$query_add_candidate=sprintf("INSERT INTO dbase (checkbox1, checkbox2) VALUES ('$values[checkbox1]', '$dates[checkbox2]')"
Now checkbox1 and checkbox2 are validated individually, beacuse they have different names. How can I check if selected is at least one of them?
Here is my HTML code:
<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox1" id="maxcheck1" value="1"/> Text1
<input class="validate[minCheckbox[1]] checkbox" type="checkbox" name="checkbox2" id="maxcheck2" value="2"/> Text2
on php ,
if(!$_POST['checkbox1'] && !$_POST['checkbox2']){
echo 'Error check at least one';
}
but what you really want is an array,
HTML,
<input type="checkbox" value="ch1" name="check[]" />
<input type="checkbox" value="ch2" name="check[]" />
php
<?php
if(empty($_POST['check'])){
echo 'Error: hey, check at least one will you!?';
}
?>
so this way you don't have to check all of them one by one, especially if you have loads of them on the same page.
NOTICE: You should also know, if checkbox is not ticked it will also not be set on the php $_POST superglobal, otherwise if it is ticked, it will show whatever the value="..." holds,
if its posted then its checked,
so if you have it in $_POST["checkbox_name"] then its checked, otherwise it wont be posted.
You can either add loads of code to reimplement control arrays in a poor way, or you can alter the code that builds your query so it can accept control arrays.
I would prefer the latter.

Count number of Checked check boxes from a php gathered check list

I'm presented with a problem using PHP and MYSQL. I have a dynamic list of options which the user can select (maximum of 3) that are added from the administration panel as shown below:
<input type="checkbox" name="<?php echo "category".$i; ?>"
value="<?php echo $cat_id; ?>" />
<?php echo $cat_name; ?><br />
<?php
$i++;
}
echo "<input type='hidden' name='num_cat' value='$num_cat' />";
?>
I now want to count how many check boxes are 'checked' and if there are more than 0 and less than 4 checked it will update the mysql table with these stored. They are stored by means of 1's and 0's. So they tick 'yes' and a 1 is stored, they tick 'no' and a 0 is stored.
I've been trying to use jQuery and Javascript but they all seem to be for Check Box Forms which have the values pre-written within a form, mine are dynamic from a database.
Many thanks for your help.
Use [] in the end of your checkbox names and use the sizeof function on the corresponding $_POST[] array in your php script.
<input type="checkbox" name="values[]" value="1" />Value 1
<input type="checkbox" name="values[]" value="2" />Value 2
sizeof($_POST['values']);
Note that the checkboxes have the same name and end with brackets (values[]). This indicates that the checkboxes belong together and are bundled as an array in php. Only the selected values will be present in the array as well.

radio button value in php

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.

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