Get previous value of select option - php

Is there a way to get the previous value of select option?
the previous value is Red
If i change it to green it will echo the selected color
How can i echo the previous color which is red?
this is my code : thanks :)
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" ;
}
?>

Use hidden field to store current value. On form post, check if the current value is different than selected value show it.
Pro tip: Always encrypt your hidden field data

store the previous value in your form as hidden value and get it
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$previous = $_POST['previous'];
}
?>
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" name="previous" value="<?php echo $selected_val; ?>"/>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :".$previous ; ?>

Since you must never trust user submitted content, another way is to build your form from PHP and do the test on the server side.
Example:
<?php
$colors = Array('Red', 'Green', 'Blue', 'Pink', 'Yellow');
?>
<form method="POST">
<select name="Color"><?php
foreach($colors as $color)
{
printf(' <option value="%1$s">%1$s</option>'."\n", $color);
}
?>
</select>
<input type="submit">
</form>
<?php
if (!empty($_POST['Color']))
{
$previous_index = array_search($_POST['Color'], $colors) - 1;
// wrap around if the color is the first
if ($previous_index < 0) {
$previous_index = count($colors);
}
printf(
"You have selected <q>%s</q>, the previous value is: %s\n",
$_POST['Color'],
$colors[ $previous_index ]
);
}
?>
The code is obviously longer than it could for educative purpose.

Here is another solution using jQuery, as a bonus you keep track of whole history and not just previous selection.
I have not tested the PHP part, but you get the idea.
HTML
<form action="#" method="post">
<select name="Color" onChange="updateHistory(this);">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" id="history" name="history" value="">
</div>
</div>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$hist = explode(',',$_POST['history']);
// pop the last value, which is current selection
array_pop($hist);
// get the last value, which now is previous
$last_valaue = end($hist);
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" . $last_valaue ;
echo 'DEBUG:<br>';
var_dump($hist);
}
?>
JS
function updateHistory(el){
var val = $(el).val();
var hist = $('#history').val();
if (hist.length > 0) {hist += ','}
hist += val;
$('#history').val(hist);
}
Example JS Fiddle
UPDATE 1:
You can further manipulate history array in PHP to your needs, for example, if you need unique values, you can use array_unique() (http://php.net/manual/en/function.array-unique.php)

Related

How to send query with select tag through url

I want send the data I received from the select tag through the url as queries so I can use it and query the database.
I have tried but the values are not showing. I am getting something like: type=&action=
This is my code
<select name="types">
<option value="2 bed room">2 bed room</option>
</select>
<select name="action">
<option value="rent">rent</option>
</select>
$type = $_POST['types'];
$action = $_POST['action'];
$query = "type={$type}&action={$action}";
<a class="site-btn fs-submit" href="search.php?<?php echo $query; ?>"> Advanced search</a>
I expected :
type=2 bed room&action=rent
Try the following code. Here, When you submit the form the whole form data will be passed to search.php and the form method is POST so you can access those data by simply calling $_POST['attribute value of name'].
HTML form:
<form class="filter-form" method="post" action="search.php" enctype="multipart/form-data">
<input type="text "class="d-block d-md-inline" placeholder="Enter State, City or Area" name="city">
<select name="types">
<option value="2 bed room">2 bed room</option>
</select>
<select name="action">
<option value="rent">rent</option>
</select>
<input type="submit" value="Advanced search">
</form>
create a PHP file (search.php):
<?php
//Do what you want here
if (isset($_POST['city'])) {
$city = $_POST['city'];
echo $city;
}
if (isset($_POST['types'])) {
$type = $_POST['types'];
echo $type;
}
if (isset($_POST['action'])) {
$action = $_POST['action'];
echo $action;
}
?>
Replace the link with a button. Attach the query params in the link to the action of the form. Your code should look like below.
<form action="search.php?<?php echo $query; ?>">
<select name="types">
<option value="2 bed room">2 bed room</option>
</select>
<select name="action">
<option value="rent">rent</option>
</select>
<?php
$type = $_POST['types'];
$action = $_POST['action'];
$query = "type={$type}&action={$action}";
?>
<button class="site-btn fs-submit" type="submit">Submit</button>
</form>

how to create php multiple forms using option dropdown?

can i create multiple form look like the one in phpmyadmin where the user can
create multiple forms by selecting a number from option dropdown list to insert multiple value
<form>
<input type="text" />
<input type="text" />
<input type="text" />
</form>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
this is the code i am using
<form action="ChangeManager.php" method="post">
<select name="prog_lang">
<?php
if($questions = $num_of_questions){
$num_of_questions = 1;
for ($i=1; $i<=$num_of_questions; $i = $i + 1){
echo "<label>السؤال رقم #".$i."</label><br>";
echo "<textarea name='"."q".$i."' rows='10' cols='50'></textarea><br>";
echo "<label>الاجابات الممكنة:</label><br>";
for($j=1; $j<=4; $j = $j + 1){
echo '<input class="choice" type="text" name="'.'choice'.$i.$j.'" id="choice'.$i.$j.'"/>';
echo '<input class="correct" type="radio" name="'.'correct'.$i.'" value="correct'.$i.$j.'"/>';
echo '<label>صحيحة</label><br>';
}
echo "<br><br>";
}
}
?>
</select>
<input style="color:blue; font-size:14pt; width:100;"type="submit" value="حفظ الاختبار" />
</form>
I suggest to use JavaScript in order to manipulate the DOM. However you can do it with PHP as well:
First you need to know how many input:
<form action="" method="post">
<select name="howManyInput">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</form>
In the 'action' page you get the value of 'howManyInput':
<?php
$howMany = $_POST['howManyInput'];
?>
Then you print the input you need in a 'for' loop:
<form action="" method="post">
<?php
for( $i=0; $i<$howMany; $i++ ){
echo '<input name="inputName'.$i.'" >';
// if you need more the 1 input for '$howMany' echo it here
}
?>
</form>
The first form take you to the page where the user can insert data.
In that page you print as many input the user select in the previous page.
When the second form is submitted it goes to a page that receive all data.

Get an output from a <select> field with $_POST when a submit button is clicked

I'm making a rock paper scissors game and players need to choose if they want to play best out of 1, 3, 5 or 7 before they start the game and i need it to work with a Select field and a submit button.
I am very new to the select tag but it would suit me best if the selected number could be exctracted with $_POST or $_GET
This is the form:
<form method="post">
<h1>Best out of </h1>
<select>
<option value="one">1</option>
<option value="three">3</option>
<option value="five">5</option>
<option value="seven">7</option>
</select>
<input type="submit" name="start" value="START" />
</form>
This is the PHP:
<?php
if(isset($_POST['start']) && isset($_POST['one']))
{
echo "do something 1";
};
if(isset($_POST['start']) && isset($_POST['three']))
{
echo "do something 2";
};
if(isset($_POST['start']) && isset($_POST['five']))
{
echo "do something 3";
};
if(isset($_POST['start']) && isset($_POST['seven']))
{
echo "do something 4";
};
?>
Give your select a name attribute
<form method="post">
<h1>Best out of </h1>
<select name="my_select">
<option value="one">1</option>
<option value="three">3</option>
<option value="five">5</option>
<option value="seven">7</option>
</select>
<input type="submit" name="start" value="START" />
</form>
After submitting your form in the PHP script you can get select value using $_POST array with index my_select ( name attribute value of the select element):
<?php
if(isset($_POST['start']) && isset($_POST['my_select']))
{
if($_POST['my_select'] === 'one'){}
....
}
?>

Get selected value ajax

First Select
<Select id="drop1" onchange="drop1(this.value)">
<option value ='1'>1</option
<option value ='2'>2</option
<option value ='3'>3</option
</select>
<div id = "txtHint1"></div>
Once a value has been selected, the value will be sent to ajax. And corresponding dropdown will be generated on another page and show in div txthint1.
Second Select
<Select id="drop2" onchange="drop2(this.value)">
<option value ='111'>111</option
<option value ='222'>222</option
<option value ='333'>333</option
</select>
<div id = "txtHint2"></div>
As the generated dropdown is another php page, how can I get what the value the user has selected to show on my current page (div txthint2)?
I will be working in php.
$value = $_GET['a'];
There are no submitted button.
Send out the second request on a successful response:
function one() {
$.ajax({
...
success: function() {
two(TheValueFromOne);
}
});
}
function two() {
$.ajax({
...
});
}
What is happening is that once the request has been made successfully, then it is automatically starting the next request right after.
However, if you are jsut passing values around form one page to another you really do not need AJAX.
FOR EXAMPLE:
test1.php:
<form action="test2.php" method="get">
Book Title <br />
<input type="text" name="booktitle" /><br />
<input type="submit" name="submit" value=" - Update Database - " />
</form>
test2.php
<body>
<? echo $_GET["booktitle"]; ?>
</body>
IN YOUR CASE:
test1.php:
<Select id="drop1" name="test1">
<option value ='1'>1</option
<option value ='2'>2</option
<option value ='3'>3</option
</select>
test2.php
<Select id="drop1">
<option selected = "<? echo $_POST['test1']; ?>"></option>
<option value ='1'>1</option
<option value ='2'>2</option
<option value ='3'>3</option
</select>
#QUESTION:
<div id = "txtHint2"><? echo $_POST['test1']; ?></div>
#POSTING WITH FORM:
<form method="post" action="test2.php" >
<Select id="drop1" name="test1" onChange="this.parentNode.submit()">
<option value ='1'>1</option
<option value ='2'>2</option
<option value ='3'>3</option
</select>
</form>

How to preSelect an html dropdown list with php? [duplicate]

This question already has answers here:
Using $_POST to get select option value from HTML
(8 answers)
Closed 6 years ago.
I am trying to get the option selected using PHP, but I ran out of ideas!
Below is the code I have tried until now:
<select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
So, what do I have to do?
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
First of all give a name to your select. Then do:
<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>
What that does is check if what was selected is the same for each and when its found echo "selected".
I suppose that you are using an array to create your select form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php #print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php #print($selected[$k]);?>>Yes</options>
<option value="2" <?php #print($selected[$k]);?>>No</options>
<option value="3" <?php #print($selected[$k]);?>>Fine</options>
Notes that I don't know:
how you are naming your input, so I made up a name for it.
which way you are handling your form input on server side, I used $_REQUEST,
You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
I have 2 php files and i made this, and it works.
(this is an example) the first code is from the one file and the second code from two file.
<form action="two.php" method="post">
<input type="submit" class="button" value="submit" name="one"/>
<select name="numbers">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
</form>
if(isset ($_POST['one']))
{
if($_POST['numbers']=='1')
{
$a='1' ;
}
else if($_POST['numbers']=='2')
{
$a='2' ;
{
else if ($_POST['numbers']=='3')
{
$a='3' ;
}
}
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.

Categories