how to get value of checked with checkbox row in php? - 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.

Related

Form with checkboxes getting all checked checkboxes

I am trying to make a random tournament generator, where I can select names from a list with checkboxes and then randominze them into a different order.
I have the following form:
<form method="post" action="<?php echo ROOT ?>HomeController/createTournament/" enctype="multipart/form-data">
<div class="form-group">
<label for="participants">Select participants</label><br>
<?php foreach($players as $p): ?>
<input type="checkbox" name="participants" value="<?php echo $p['name'];?>"> <?php echo $p['name'];?><br>
<?php endforeach; ?>
</div>
<button type="submit" class="btn btn-primary btn-block" name="create">Show participants</button>
</form>
This form show's a checkbox and behind the checkbox the name of the participant.
This is my method:
public function createTournament() {
if(isset($_POST["create"])) {
$participants = $_POST['participants'];
}
include('app/views/showTournament.php');
}
That means I am saving the checked ones into $participants, right?
In the file showTournament, I know have access to $partipants.
I try to var_dump $particpants and it shows me:
string(6) "Onlyoneselected name"
So I tried a foreach, to get ALL of the selected names.
<?php
foreach($participants as $p) {
echo $p;
}
;?>
The foreach isn't showing anything, but the file has access to $participants. I want all the names on my screen, so I can start randomizing them. What do I do wrong?
<input type="checkbox" name="participants"
This line here is the root of your problems.
Because every checkbox has the same name, the value of $_POST['participants'] gets overridden for each checkbox in the list.
If you change that snippet to:
<input type="checkbox" name="participants[]"
Then $_POST['participants'] becomes an array of all checked values.
You need multiple checkbox values.
And therefore, HTML name of the input should be multiple (array)
<input type="checkbox" name="participants" will return string, only latest submitted value.
<input type="checkbox" name="participants[]" will return array of all submitted values.
So, replacing name="participants" to name="participants[]" will work.

How to customize query string with multiple checkboxes under same name?

I have a form with a get method that is used for searching items (vehicles) from the database. The form has multiple checkbox sets. Like user can filter the search results by selecting multiple makes from the makes checkbox list. Similarly user can also apply filter on car models from models chebox list and so on. There are about 10 such filters on the form.
Here is the code snippet of the my form:
<form action='./search' method='get'>
<input type='checkbox' name='make[]' value='BMW'/>
<input type='checkbox' name='make[]' value='Mercedes'/>
<input type='checkbox' name='make[]' value='Honda'/>
<input type='checkbox' name='make[]' value='Toyota'/>
<input type='checkbox' name='make[]' value='Porsche'/>
......//Remaining Form
</form>
Similarly for car models I have similar markup...There are such 10 filters all implemented using checkbox list.
Now coming towards the problem, when I submit the form I get URL like this:
http://localhost/auto/search?make=BMW&make=Mercedes&make=Honda
This is forming a type of query string which I don't like i.e it is repeating 'make' attribute for all the checked values and will do so for remaining 9 filters as well. This will result in very long ugly looking URL.
What I want is that my URL should look something like this:
http://localhost/auto/search?make=BMW,Mercedes,Honda
This is much better but I don't know how would I achieve that. What I have tried is to get all the values of checked boxes and then write them into hidden field value so that I get my desired format in the query string. And unset all the checboxes selected by the user and submit the form with hidden field containing all the selections. But the problem is when the form is submitted I get two 'make' fields in the URL like:
http://localhost/auto/search?make=&car_makes=BMW,Mercedes,Honda
where car_makes is the hidden input field in which I wrote all the selections in value attribute.
Any solution to this? So that make attribute does not get submitted, but it does, since it is the part of the form.
Thanks.
Try these:
<html>
<head>
<script type="text/javascript">
function buildup(){
var makes=document.getElementsByName('make[]');
var m=document.getElementById('make');
m.value='';
ms='';
for (var i = makes.length - 1; i >= 0; i--) {
if(i>0)ms=ms+',';
ms=ms+makes[i].value;
}
m.value=ms;
document.getElementById('form').submit();
}
</script>
</head>
<body>
<input type='checkbox' name='make[]' value='BMW'/>
<input type='checkbox' name='make[]' value='Mercedes'/>
<input type='checkbox' name='make[]' value='Honda'/>
<input type='checkbox' name='make[]' value='Toyota'/>
<input type='checkbox' name='make[]' value='Porsche'/>
<form action='./search' id='form' method='get'>
<input type='hidden' name='make' id='make'>
<input type='button' value='submit' onclick='buildup()'>
</form>
</body>
If you don't want the make inputs to get submitted, you should disable them before the form gets submitted (or remove the name attribute...).
It would probably be easiest to add a class to all inputs you don't want to submit and then do something like this right before the form submit:
html:
...
<input type='checkbox' name='make[]' value='BMW' class='dont-send-class' />
...
js:
$('.dont-send-class').prop("disabled", true);
// now you can submit the form

checkboxes in php form doesn't work

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

Tesing if at least two checkboxes are checked then insert the values into data base

I am using html,php, javascript,mysql and wampserver.
I have 3 checkboxes, the user should maximum check two , then I insert the two choices into my database.
I have declared 3 checkboxes with different name attribute (different => because I have declared 3 variables in my php code)
but then when I want to insert the validation using javascript (to validate that just maximum 2 checkboxs are checked)
I found that I should declare the 3 checkboxes with the same attribute name
My question is :
To insert the user choises into my database I should declare 3 variables so 3 different name attribute,
and to validate checkboxes :2 at least are checked I have to use the same name attribue
Is there another solution that I dont know?
HTML code:
<input type="checkbox" value="workshop1Day1" id="workshop" name="workshop1Day1" />Workshop I
<input type="checkbox" value="workshop2Day1" name="workshop2Day1" />Workshop II
<input type="checkbox" value="workshop3Day1" name="workshop3Day1" />Workshop III
php code
$workshop1Day1 = $_POST["workshop1Day1"];
$workshop2Day1 = $_POST["workshop2Day1"];
$workshop3Day1 = $_POST["workshop3Day1"];
$requete = "INSERT INTO Participant (workshop1Day1,workshop2Day1,workshop3Day1)
VALUES ('$workshop1Day1', '$workshop2Day1', '$workshop3Day1')";
The java script that I found (use the same value for the name attribute
Checkbox Validations
thank you
This might be helpful for you:
<script>
function checkifclicked()
{
//alert($('input[name=cb]').val());
var checkboxs=document.getElementsByName("cb");
var okay=false;
var count = 0;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
count++;
}
}
if(count > 1){
okay=true;
}
if(!okay){
alert("Please check at least two checkbox");
return false;
}
}
</script>
<form name="send_email" id="send_email" action="send_email.php" onSubmit="return checkifclicked()" method="post">
<div id="checkbox">
<input type="checkbox" id="1" name="cb"/><br/>
<input type="checkbox" id="2" name="cb"/><br/>
<input type="checkbox" id="3" name="cb"/><br/>
<input type="submit" value="Submit"/>
</div>
</form>
Codepad Demo>>

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