select multiple options - php

banging my head against the wall for something seemingly dead simple.
Here it is:
<html>
<head></head>
<body>
<form method="post" action="action.php">
<div><input type="checkbox" name="test" value="Newspaper"> <span >Newspaper</span></div>
<div><input type="checkbox" name="test" value="PC"> <span >PC</span></div>
<div><input type="checkbox" name="test" value="Home"> <span >Home</span></div>
<div><input type="checkbox" name="test" value="Dont_know"> <span >dnunno</span></div>
<input type="submit" name="Submit" value="send">
</form>
</body>
</html>
But when I select more then one option. I see in my print_r($_POST); statement only the last selected option in stead of all selected options.
How should I deal with this?
update:
I checked the rest of my code and i saw that this is done by some JavaScript.
else if (aform.validatorArr[i][4] == "checkbox") {
var fvs = "";
eval("var chkbArray=aform." + aform.validatorArr[i][1] + ";");
if (aform.validatorArr[i][2] == "cb_true") {
for (k = 0; k < chkbArray.length; k++) {
if (chkbArray[k].checked) {
fvs += chkbArray[k].value;
console.log(fvs);
}
}
if (fvs == false) {
s += aform.validatorArr[i][3] + "\n";
}
}
}
That's why the [] is not added in my html. But how could I modify this code so that it will take all options?

Put [] after the name:
<input type="checkbox" name="test[]" value="Newspaper">
See PHP FAQ for more details.

Related

Save checked values on page refresh?

Ive saved form data with ajax and php, reusing the data from the database.
However the way I am approaching this is different, there is no database, so some insight would be great.
I am emailing form data, all the data is just simple checkboxes, the values are either 0 or 1. When the user refreshes the page id like to keep the checked values.
I guess without a database I would need to use cookies, and the only way to avoid cookies would be ajax and a database (strictly my logic, not sure if true), this is why I am asking, I just want a simple solution.
Form snippet:
<input name="sharks" type="hidden" value="0">
<input name="sharks" type="checkbox" value="1" id="sharks" '.$VALUE ? ' checked="checked"' : ''.'>
The php part of that input is shaky, Id like to question whether the value is 0 or 1, if its 1 then its checked if its 0 then empty.
Getting it from the database would be easier but not so sure since there is no database, Im guessing cookies would come into place.
Sorry if this last part is shaky but im a little unsure and dont know where to look.
Using Sessions:
session_start();
if(isset($_POST['submit'])) {
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form
<form action="<?php the_permalink(); ?>" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<?php
if ($_SESSION['value'] == 1) {
$checked = 'checked="checked"'; }
?>
<li>
<input name="personalization_result[memory_0]" type="hidden" value="0">
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" value="0">
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_2]" type="hidden" value="0">
<input name="personalization_result[memory_2]" type="checkbox" value="1" id="personalization_result_memory_2" <?php $checked ?> >
</li>
This code stores the data in a session:
<?php
session_start();
if(isset($_POST['submit']))
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
}
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
print ' checked="checked"';
}
print ">";
?>
<br>
<input type="submit" name="submit" value="Save" />
</form>
Worked for me, keeping the checkbox checked after I closed and opened the browser again. After some testing I added a rather complex if to avoid the undefined variable notice. Now the set part seems robust.
You can either use session or cookie. Basically you will access using $_COOKIE or $_SESSION. I would rather say that this is easier than using a database.
For cookies have a look at setcookie (http://www.php.net/setcookie)
For sessions: http://php.net/manual/en/book.session.php
I would use local storage or session storage, this is a client side memory storage location that persists even if the page is refreshed, it is integrated into html5.
Here is a nice tutorial about it:
http://www.w3schools.com/html/html5_webstorage.asp
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Persist checkboxes 1</title>
<script>
window.jQuery || document.write("<script src='jquery-.1.1.js'><\/script>");
</script>
<script>
$(document).ready(function()
{
$('#me').click(function()
{
var seloption = $('input[type="checkbox"]:checked');
if (seloption.length > 0)
{
var abc = seloption.length + "checked \n";
//alert(abc);
i = 0;
seloption.each(function()
{
abc = abc + $(this).text(seloption[i]) + "<br>";
}
);
$('#msg').html(abc);
}
}
);
}
);
</script>
</head>
<body>
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<div>
<label for="option4">Option 4</label>
<input type="checkbox" id="option4">
</div>
<div>
<label for="option5">Option 5</label>
<input type="checkbox" id="option5">
</div>
<div>
<label for="option6">Option 6</label>
<input type="checkbox" id="option6">
</div>
<div>
<label for="option7">Option 7</label>
<input type="checkbox" id="option7">
</div>
<div>
<label for="option8">Option 8</label>
<input type="checkbox" id="option8">
</div>
<div>
<label for="option9">Option 9</label>
<input type="checkbox" id="option9">
</div>
<button type="button" id="me">Submit</button>
<div id="msg">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
$(":checkbox").on("change", function() {
var checkboxValues = {};
$(":checkbox").each(function() {
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, {expires: 1, path: '/'});
});
function repopulateCheckboxes() {
var checkboxValues = $.cookie('checkboxValues');
if (checkboxValues) {
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
</script>
</body>
</html>

Checkbox to act like radio button, check first four or last four checkboxes but not both- javascript?

I am having a problem in javaScript.
I want to check either any of the first 4 checkboxes or any of the last four checkboxes to true.
here in my code if i check any one of the first four or all first four of the checkbox, last four checkboxes are disabled.
now after checking any one or the first four last four are unclickable.
i want them to be clickable and the first four checkboxes to be unchecked.
please correct my code
Here is my code and thanks in advance
<html>
<head>
<title>FooBar</title>
<script language="javascript">
function checkOnly(checked)
{
if(document.myForm.elements[0].checked == true || document.myForm.elements[1].checked == true || document.myForm.elements[2].checked == true || document.myForm.elements[3].checked == true)
{
document.myForm.elements[4].checked = 0;
document.myForm.elements[5].checked = 0;
document.myForm.elements[6].checked = 0;
document.myForm.elements[7].checked = 0;
}
}
</script>
</head>
<body>
<form name="myForm">
<?php for($i=1;$i<=8;$i++){ ?>
<input type="checkbox" name="cb" id="cb" value="1" onClick="checkOnly(this)">
<?php } ?>
</form>
</body>
</html>
Consider using the the 'checked' parameter of you checkOnly function to determine which checkbox the user checked (maybe give them unique ids). As your logic stands now, if you check the first checkbox, it will clear out the checkboxes on the last four. Then if you check the last checkbox, it will still clear out the last four checkboxes because the first checkbox is still checked. This makes it look like the last four checkboxes are disabled even though they aren't.
For example:
<html>
<head>
<title>FooBar</title>
<script language="javascript">
function checkOnly(myCheckbox) {
var checkboxChanged = false;
var checkedTotalValue = 0;
var changedTotalValue = 0;
for(var i = 0; i < document.myForm.elements.length; i++) {
if(document.myForm.elements[i].name != myCheckbox.name) {
if(document.myForm.elements[i].checked == true) {
checkboxChanged = true;
changedTotalValue += parseInt(document.myForm.elements[i].value);
}
document.myForm.elements[i].checked = false;
}
if(document.myForm.elements[i].checked == true) {
checkedTotalValue += parseInt(document.myForm.elements[i].value);
}
}
if(checkboxChanged) {
alert('Checked: ' + checkedTotalValue + ', Changed: ' + changedTotalValue);
}
}
</script>
</head>
<body>
<form name="myForm">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup1" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
<input type="checkbox" name="checkboxGroup2" id="cb" value="1" onClick="checkOnly(this)">
</form>
</body>
</html>

How to append multiple values to a single parameter in html form?

Assuming I have the following form:
<form action="process.php">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit"/>
</form>
What would normally happen is after clicking on the URL, the browser redirects to:
process.php?option1=oats&option2=beans&parameter=a
How do I make it such that when the submit is clicked all the checkboxes end up as part of the "parameter", but separated by commas? So in other words it would be:
process.php?parameter=a,oats,beans
Best solution with minimal javascript/jquery/html is best if no html solution.
If you want several values in one parameter, you have to name it like parameter[]
f.e.:
<form action="process.php">
<input type="checkbox" name="parameter[]" value="oats"> Oats
<input type="checkbox" name="parameter[]" value="beans"> Beans
<input type="hidden" name="parameter[]" value="a"/>
<input type="submit" value="Submit"/>
</form>
More or less here the idea:
first form, 1 hidden input will catch all the vaules of second and void form
<script type="text/javascript">
function myfunc(){
$('#void input').each(function(id,elem){
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
alert("VAL "+$("#res").val());
$("#real").submit();
return false;
}
</script>
<form id="real" action="process.php">
<input id="res" type="hidden" name="parameter" value=""/>
</form>
<form id="void">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit" onClick="javascript:myfunc()"/>
</form>
add some fix, submit the right form. Tested on jsfiddle:
JsFiddel "working" example
ADD SINGLE FORM VERSION
You've to know the name of the field, and ignore the other params in the answer
<script type="text/javascript">
function myfunc(){
// can use more selector
$('#real input').each(function(id,elem){
// append the data to this field so no need to process it
if(this.id == 'res'){
return;
}
// here I concat the values
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
alert("VAL "+$("#res").val()); // remove me
$("#real").submit();
return false;
}
</script>
<form id='real' method='POST' action="#">
<input type="checkbox" name="option1" value="oats"> Oats
<input type="checkbox" name="option2" value="beans"> Beans
<input id="res" type="hidden" name="parameter" value="a"/>
<input type="submit" value="Submit" onClick="javascript:myfunc()"/>
</form>​
There is a very useful method to use for dynamic data grouping.
<form action="file.php" method="post">
<?php for ( $i = 0; $i < count( $something ); $++ ) { ?>
<input type="checkbox" name="<?php $something[$i]; ?>[]" value="user_id"> Oats
<input type="checkbox" name="<?php $something[$i]; ?>[]" value="user_name"> Beans
<?php } ?>
<input type="submit" value="Submit"/>
</form>
I was really only interested in checkboxes that were actually checked - so I built myfunc() from the other examples like this:
function myfunc(){
$('#void input[type="checkbox"]').each(function(id,elem){
if ( ! $(this).is(':checked') ) return;
b = $("#res").val();
if(b.length > 0){
$("#res").val( b + ',' + $(this).val() );
} else {
$("#res").val( $(this).val() );
}
});
var stuff = $("#res").val();
if ( stuff.length < 1 ) {
alert('Please select at least one');
} else {
$("#real").submit();
}
}

Get all multiple listbox values

I have a multiple selection listbox in which I insert items using javascript. At a certain point I need to get the values of all entries (both selected and unselected).
I'm currently using this code:
<form method="post" action="?page=test" name="something">
<select name="thelist[]" id="selOriginalWindow" size="5" multiple="multiple">
</select>
<input type="button" value="Добави" onclick="openInNewWindow();" />
<input type="submit" value="Get" />
</form>
<?
if ($_GET['page']=="test") {
$thelist=$_POST['thelist'];
var_dump($thelist);
}
?>
Javascript inserts the values, but PHP only gets the selected items' value. How do I get the value of all of the items in that listbox?
This did the trick:
function selectAll(selectBox,selectAll) {
if (typeof selectBox == "string") {
selectBox = document.getElementById(selectBox);
}
if (selectBox.type == "select-multiple") {
for (var i = 0; i < selectBox.options.length; i++) {
selectBox.options[i].selected = selectAll;
}
}
}
</script>
<form method="post" action="?page=test" name="something">
<select name="thelist[]" id="selOriginalWindow" size="5" multiple="multiple">
</select>
<input type="button" value="Добави" onclick="openInNewWindow();" />
<input type="submit" value="Get" onclick="selectAll('selOriginalWindow',true)" />
</form>
<?
if ($_GET['page']=="test") {
$thelist=$_POST['thelist'];
var_dump($thelist);
}
?>
The post variable will only contain those values you select, therefore if you want to use the same methodology to send ALL values you will need to add an additional field to your form which includes ALL the values. You can then read all values from this.
One way would be to use <input ='hidden' value='arrayofallvalues' name='allvalues'/>
So you could have the following:
<?
$select_values=array('value1', 'value2','value3');
?>
<form method="post" action="?page=test" name="something">
<select name="thelist[]" id="selOriginalWindow" size="5" multiple="multiple">
<?
for ( $i= 0; $i< count($select_values); $i++) {
echo "<option value=".$select_values[$i].">".$select_values[$i]."</option>";
}
?>
</select>
<input ='hidden' value='".implode(",",$select_values)."' name='allvalues'/>
<input type="button" value="Добави" onclick="openInNewWindow();" />
<input type="submit" value="Get" />
</form>
<?
if ($_GET['page']=="test") {
$thelist=$_POST['thelist'];
$all_select_values=explode(",",$_POST['allvalues']);
var_dump($thelist);
}
?>
What this will do is mean that every time the form submits, you can use explode() to create an array of the available values for the selct box.

Unlimited fields in PHP?

How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.
That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Categories