Get all multiple listbox values - php

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.

Related

How to update a forms text fields when a drop gets updated using php

I have a form in a php page that I want to have updated as the drop down is changed. Here is the code for the form:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
Currently, the form gets its values for the 2 text fields (VersionNumber and Notes) from outside the form. I would like to have them be obtained as the form is created based on what the first drop down (Name) has selected and then update if that drop down gets changed.
I thought of adding some PHP to the form to help, but it doesn't work. Here is what I tried:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<?php
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
?>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
I don't know how to capture what is in the drop down to change the SQL that is pulling the data. I thought of possibly just pulling all of the rows back and then doing a search against it once the form is built, but I still don't know how to capture when the drop down changes and then update the 2 text boxes.
UPDATE
I now have a new file named UpdateAdminVersion.php this is what is has:
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
$data = $VersionNumber;
echo json_encode($data);
I also added the following script to the previous file with the form:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
parameter1: "ReportDashboard Dev",
parameter2: $("#VersionNumber").val()
},
function (data, status)
{
aconsole.log(data)
$("#Notes").val(data);
});
});
I must still be missing something because nothing happens when I change the drop down.
UPDATE 2
I've changed the script to this:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
WebName: $('#WebName').val(),
VersionNumber: $("#VersionNumber").text()
},
function (data, status)
{
console.log(data)
$("#Notes").val(data);
success: alert ("Number 2 is successful!");
});
success: alert ("Number 1 is successful! \n" + WebName + "\n" + VersionNumber);
});
I get the alert Number 1 is successful!, but the WebName and VersionNumber variables return [object HTMLSelectElement] and [objectHTMLInputElement] respectively. How do I return the actual values?
And how do I use them in the UpdateAdminVersion.php file?
For starters you can use jqueryUI Autocomplete to feed Select tag with options.
Then use onchange event to capture dropdown changes.
<select onchange="myFunction()">
when event is triggered retreive data from db using Ajax, on success modify your form fields accordingly.
Look at this Fiddle give your own parameters, should work.

how to store the value from html dropdwon list to use in the same page

I have this code -
<form method="post" action="generate.php">
<select name="test" id="Test">
<?php
$i=0;
foreach($testName as $name){
?>
<option value="<?php echo $name;?>"><?php echo $testName[$i];?></option>
<?php $i++; } ?>
</select>
<input type="submit" name="submit" value="Generate">
</form>
How I can store the value selected by user in a way that I can use it in the same php page?
Store the value in a hidden field with javascript/jquery like:
<input type="hidden" name="hidden" id="hidden">
and call an onchange event on select element.
<select name="test" id="Test" onchange="test()">
Write corresponding js function,
<script>
function test()
{
var selectedval=$("#Test").val(); // get selected value
$("#hidden").val(selectedval); // set the value of hidden field
}
</script>
Store the value in a hidden field with javascript/jquery like:
<input type="hidden" name="hidden" id="hidden">
Write some jQuery Code to assign value to hidden field on change on drop down:
<script src="PATH/TO/JQUERY"></script>
<script>
$(function(){
$("#Test").live("change", function() {
$("#hidden").val($(this).val());
});
});
</script>
You can set an onchange handler to the form element to run javascript when the form option is selected. Here is an example (using your code):
<html>
<head>
</head>
<body>
<select name="test" id="Test" onchange="formChangeFunc(this)">
<?php
$i=0;
foreach($testName as $name)
{
?>
<option value="<?php echo $name;?>"><?php echo $testName[$i];?></option>
<?php
$i++;
}
?>
</select> <input type="submit" name="submit" value="Generate">
</form>
<script>
function formChangeFunc(sel) {
alert(sel.value);
document.getElementById('divIdToInsert').innerHtml(sel.value);
}
</script>
<div id="divIdToInsert"></div>
</body>
</html>
The example should give you an alert popup when you change the option. This should also insert the value into the specified div container.

can i add new HTML element(eg. radio, checkbox,dropdown) to current a file on form submission?

i have one file which contains two fileds both have one form, on a second form i have one drop down for selection what user want(eg. radio, checkbox,dropdown) and a label to that choice,so here can i add new HTML element(eg. radio, checkbox,dropdown) to current a file on form submission???if Yes t
Yes you can, by the use of ajax.
not by the form post
Not sure if i got you right, your text is very confusing.
Page #1
<form action="page2.php" method="post">
<input type="checkbox" name="addcheckbox" value="1"> Add a checkbox<br>
<input type="checkbox" name="adddropdown" value="1"> Add a dropdown<br>
<input type="submit">
</form>
Page #2
echo '<form [...]>';
if( $_POST['addcheckbox'] == 1) echo '<input type="checkbox" name="whatever" value="1"> checkbox';
if( $_POST['adddropdown'] == 1) echo '<select name="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>';
echo '</form>';
Do it through javascript, don't use form submit, it will take time.
First form
<div id="first_form">
<form id=="firstform">
<input type="text" />
<input type="text" />
</form>
</div>
Second form that will generate element
<form id="secondform">
<select id="choice" onchange="createElement(this.value);">
<option value="radio">Radio</option>
<option value="checkbox">checkbox</option>
<option value="dropdown">dropdown</option>
</select>
</form>
Javascript code
<script type="text/javascript">
function createElement(element) {
var html = '';
if(element=='radio') {
html = "<input type='radio' />";
}
else if(element=='checkbox') {
html = "<input type='checkbox' />";
}
if(element=='dropdown') {
html = "<select><option>abc</option></select>";
}
//use jquery
$("#first_form").append(html);
}
</script>
Not sure what you are asking.
You call a function onSubmit (more here). And in that function you can dynamically add form elements via JavaScript if that is what you need.
Use createElement to create and appendChild to add the elemet where you want it.
More info here
Use jquery.It is the best wat to append element to the same page.

Can I submit from a second form and retain POST data from the first?

Hopefully I'm making this more difficault then it has to be. Here is what I'm trying to do. I have a form that does a POST and returns data. I have a second form that then asks the user a yes/no question based on data from the first form. Is it possible to capture the POST data from the first form submission and pass it along with the second form POST?
Here is my scenario
if ($_POST['button_1']) {
$params = $_POST;
print_r($_POST);
// process form data
}
if ($_POST['button_2']) {
// Retain the POST data from the first submission
$new_params = $params . $_POST;
print_r($new_params);
// process form data and do some additional stuff
}
<form id="form_1" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
...
<input type="submit" value="Button" name="button_1" id="button_1"/>
</form>
<form id="form_2" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
...
<input type="submit" value="Button" name="button_2" id="button_2"/>
</form>
Is there a way to do this easily or am I over complicating this?
You can either use a hidden field in your second form, or sessions. Start reading here:
http://www.php.net/manual/en/book.session.php
Yes, the standard way is to use type = "hidden" fields to pass this context data onto the second form. There are lots of worked examples to see how to do this. View the source of this HTML page or any other with forms on them and search for "hidden" to see how the applications do this.
There are a few ways to "fake" this.
Have the first form submit to itself and just load the $_REQUEST variables and use them to populate the second form with the appropriate data/options.
have the 2nd form loaded via ajax once the first is submitted and use javascript to grab the current form variables and provide them to the ajax function.
Which method would you prefer?
UPDATE:
This is long, but a working example
<!DOCTYPE html>
<html>
<body>
<form name="first" method="post">
<input type="hidden" name="action" value="firstformdone">
<div style="width:100px;float:left;">
Age:
</div>
<div style="width:200px;float:left;margin-left:20px;">
<input type="text" name="age">
</div>
<div style="clear:both;"></div>
<div style="width:100px;float:left;">
Name:
</div>
<div style="width:200px;float:left;margin-left:20px;">
<input type="text" name="name">
</div>
<div style="clear:both;"></div>
<br>
<?PHP
if (!$_REQUEST['action'] == "firstformdone") {
?>
<input type="submit" value="contine">
<?PHP
}
?>
</form>
<?PHP
if ($_REQUEST['action'] == "firstformdone") {
?>
<form name="second" action="something_else.php" method="post">
<input type="hidden" name="age" value="<?PHP echo $_REQUEST['age']; ?>">
<input type="hidden" name="name" value="<?PHP echo $_REQUEST['name']; ?>">
<div style="width:150px;float:left;">
Preferred games:
</div>
<div style="width:200px;float:left;margin-left:20px;">
<select name="games">
<option value="">Select games</option>
<?PHP
if ($_REQUEST['age'] <= 10) {
?>
<option value="tlddlywinks">Tiddly Winks</option>
<option value="Jacks">Jacks</option>
<option value="Go-Fish">Go-Fish</option>
<option value="Hid-And-Go-Seek">Hid-And-Go-Seek</option>
<?PHP
} else {
?>
<option value="Halo">Halo</option>
<option value="StarWars">The Old Republic</option>
<option value="LaserTag">Laser Tag</option>
<option value="spin-the-bottle">spin-the-bottle</option>
<?PHP
}
?>
</select>
</div>
<div style="clear:both;"></div>
<br>
<input type="submit" value="Next!">
</form>
<?PHP
}
?>
</body>
</html>
You need to package the data from the first form up for resubmission. You can use a hidden fields for that job:
foreach ($_POST as $key => $value) {
print "<input type='hidden' name='".htmlspecialchars($key, ENT_QUOTES, "UTF-8")."' value='".htmlspecialchars($value, ENT_QUOTES, "UTF-8")."'>";
}

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