PHP keep dropdown value after submit - php

I have the following code for a simple calculator. The code works fine, but I want the value in the dropdown list to stay there after submitted. How would I do this?
Essentially, I want the operator to stay selected once the calculation has been done. At the moment, it just shows a '+', even if the sum is 25 / 5.
<?php
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$operation = $_POST['operator'];
Switch ($operation) {
case 'add': $answer = $number1 + $number2;
break;
case 'minus': $answer = $number1 - $number2;
break;
case 'divide': $answer = $number1 / $number2;
break;
case 'multiply': $answer = $number1 * $number2;
break;
}
?>
<form name='calculator' method='post' action=''>
<table>
<tr>
<td>
<input name="number1" type="text" value="<?php i if(isset($_POST['number1'])) { echo htmlentities($_POST['number1']);}?>" />
</td>
<td>
<select name="operator">
<option value="add">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">x</option>
</select>
</td>
<td>
<input name="number2" type="text" value="<?php if(isset($_POST['number2'])) { echo htmlentities($_POST['number2']);}?>" />
</td>
<td>
<input name="submit" type="submit" value="=" />
</td>
<td>
<input name="" type="text" value="<?php echo $answer ?>" />
</td>
</tr>
</table>

You have to set the selected attribute for the option that was submitted. So you have to check the submitted value for each option. In my solution I am using the ternary operator to echo the selected attribute only for the correct operator.
<select name="operator">
<option value="add" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'add') ? 'selected' : ''; ?>>+</option>
<option value="minus" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'minus') ? 'selected' : ''; ?>>-</option>
<option value="divide" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'divide') ? 'selected' : ''; ?>>/</option>
<option value="multiply" <?php echo (isset($_POST['operator']) && $_POST['operator'] == 'multiply') ? 'selected' : ''; ?>>x</option>
</select>
The code above is somewhat repetitive. It keeps repeating a lot of code and html. It would be great if we could factor out the repetitive stuff. Luckily we can do that by creating an array that stores the options and loop through them using a foreach, like this:
<?php
$options = [
'add' => '+',
'minus' => '-',
'divide' => '/',
'multiply' => 'x'
];
?>
<select name="operator">
<?php foreach ($options as $key => $label) { ?>
<option value="<?= $key ?>" <?= (isset($_POST['operator']) && $_POST['operator'] == $key) ? 'selected' : '' ?>><?= $label ?></option>
<?php } ?>
</select>

Related

Focus on HTML Select dropdown option after GET request

So I am making a programme and I am submitting a form to itself. This programme is a very basic calculator as I am new to HTML and PHP. I am trying to make it so that when you submit the form, the Select dropdown will remain on the most recently used operator.
For example, if I make the calculator do '5 + 5', then I want the submitted form to keep the operator dropdown on '+'.
Here is my code:
<?php
// grab the form values from $_HTTP_GET_VARS hash extract($_GET);
// first compute the output, but only if data has been input if(isset($calc) && $operator == "multiply") { // $calc exists as a variable
$prod = $x * $y; } elseif (isset($calc) && $operator == "plus") {
$operator = $plus;
$prod = $x + $y; } elseif (isset($calc) && $operator == "minus") {
$operator = "minus";
$prod = $x - $y; } elseif (isset($calc) && $operator == "divide") {
$sign = "/";
$prod = $x / $y; } else { // set defaults
$x=0;
$y=0;
$prod=0; } ?>
<html> <head>
<title>PHP Calculator Example</title> </head>
<body>
<h3>PHP Calculator (Version 1)</h3>
<p>Multiply two numbers and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<label for="x">x = </label>
<input type="text" name="x" id="x" size="5" value="<?php print $x; ?>"/>
<select name="operator" id="operator">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="divide">/</option>
<option value="multiply">*</option>
</select>
<label for="y">y = </label>
<input type="text" name="y" id="y" size="5" value="<?php print $y; ?>"/>
<input type="submit" name="calc" value="Calculate"/>
</form>
<!-- print the result -->
<?php if(isset($calc)) {
print "<p>x $sign y = $prod</p>";
} ?>
</body> </html>
In order to remain on option selected in the select element
The option has to have an attribute "selected"
<select name="operator" id="operator">
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "plus"){echo "selected";} ?> value="plus">+</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "minus"){echo "selected";} ?> value="minus">-</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "divide"){echo "selected";} ?> value="divide">/</option>
<option <?php if(isset($_GET['operator']) && $_GET['operator'] == "multiply"){echo "selected";} ?> value="multiply">*</option>
</select>
Hope that it will help you.
A possible solution employing javascript would be this
<?php
if(isset($_GET['operator'])) {
?>
<script>document.getElementById("operator").value = '<?=$_GET['operator']?>';</script>
<?php
}
?>

Dropdown menu does not stay selected via php after refreshing the page

The following script would let the user to chose between on and off. The problem is that the selected value does not stay selected after refreshing the page. Any idea how to fix this?
<form action="Conf.php" name="Calculation" method="post">
<?php
if (isset($_POST['Submit1']))
{
$Wave = $_POST['WaveHMap'];
}
?>
<?php
$attr = 'selected="selected"';
?>
Wave Height Maps:
<select selected="selected" name="WaveHMap" VALUE="<?PHP print $Wave ; ?>">
<?php $attr= 'selected="selected"'; ?>
<option VALUE="On"<?php echo $Wave == 'On' ? $attr : ''; ?>>On</option>
<option VALUE="Off"<?php echo $Wave== 'Off' ? $attr : ''; ?>>off</option>
</select>
<Input Type="Submit" Name="Submit1" Value="Save Parameters">
</form>
Try this
<select name="WaveHMap" >
<option VALUE="On" <?php echo $Wave == 'On' ? 'selected' : ''; ?>>On</option>
<option VALUE="Off" <?php echo $Wave== 'Off' ? 'selected': ''; ?>>off</option>
</select>

how to add check bo0x in selection box with multiple selection box

I used selection box with multiple selection now the problem is that it is selectable with ctrl+click of mouse. It is work properly but not that much prefrble to me and lookes like simple selection box and user cant get that its multiple selector not single.so thats why i want it with check box so user easly get it is multiple selector.please give apropriate solution thanks in advanced...
<select class="selopt" id="selPreLoc" name="SelPreLoc[]" multiple="multiple" size=5>
<option label="No Preference">No Preference</option>
<?php
//<option value=-1 selected>No Preference</option>
while ($rec = mysql_fetch_array($GetCityRecord)) {
if ($rec['City_Id'] == 30 || $rec['City_Id'] == 34 || $rec['City_Id'] == 35) {
$others[$rec['City_Id']] = $rec['City'];
continue;
}
?>
<option value="<?php $rec['City_Id']; ?>" <?php echo (isset($_POST['SelPreLoc']) && in_array($rec['City_Id'], $_POST['SelPreLoc'])) ? 'selected' : '' ?>>
<?php echo $rec['City']; ?>
</option>
<?php
}
foreach ($others as $ind => $val) {
?>
<option value="<?php echo $ind; ?>" <?php echo (isset($_POST['SelPreLoc']) && in_array($ind, $_POST['SelPreLoc'])) ? 'selected' : '' ?>>
<?php echo $val; ?>
</option>
<?php }
?>
</select>
<label class="formtxt" valign="bottom">Use Ctrl + Click to multi-select.</label></td>
I got many other solution with using div or other.
but i just want it with select option only is it posible if yes how .andi can fetch the result in mysql and i want that result with comma seprator in mysql.
My code is not tested, since i do not have the data, but based on your logic, you can use it like this:
$theOthers = array(30, 34, 35);
while ($rec = mysql_fetch_array($GetCityRecord)) {
if (in_array($rec['City_Id'], $theOthers)) {
$others[$rec['City_Id']] = $rec['City'];
continue;
}
$checked = '';
if (isset($_POST['SelPreLoc']) && in_array($rec['City_Id'], $_POST['SelPreLoc'])) {
$checked = 'checked="checked"';
}
?>
<input type="checkbox" name="city[]" value="<?php $rec['City_Id']; ?>" <?php echo $checked; ?> /> <?php echo $rec['City']; ?> <br />
<?php
}
foreach ($others as $ind => $val) {
$checked = '';
if (isset($_POST['SelPreLoc']) && in_array($ind, $_POST['SelPreLoc'])) {
$checked = 'checked="checked"';
}
?>
<input type="checkbox" name="city[]" value="<?php echo $ind; ?>" <?php echo $checked; ?> /> <?php echo $val; ?> <br />
<?php
}
NOTE: I improved your code a littlebit with the $theOthers array, i think it's more readable.
When form is submitted, let's var_dump($_POST["city"]);

Issue with setting the default value and remembering the values in select box in PHP

<form name="search" method="post" >
Seach for: <input type="text" name="find" value="<?php echo (isset($_POST['find']) ? $_POST['find'] : ''); ?>" /> in
<Select NAME="field">
<Option VALUE="category1" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category1') ? 'selected="selected"': ''; ?>>category1</option>
<Option VALUE="category2" <?php echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"': ''; ?>>category2</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
<?php
if(!empty($_POST)){
$options = array('category1'=> array('1' => 'dog', '2' => 'cat'), 'category2' =>array('1'=>'flower', '2'=>'grass'));
$input = trim($_POST['find']);
$category = $_POST['field'];
$output = $options[$category][$input];
echo $output;
}
?>
Question:
How could I make category2 to be the default value for the select box instead of category1? I tried this:
<Option VALUE="category2" <?php
echo (isset($_POST['field']) && $_POST['field'] === 'category2') ? 'selected="selected"' : '';
?> selected = "selected">category2</option>
but it breaks my function. When I input 1 and select category1, after I clicked search, the select box changed to category2. That is not what I want. I want this function to perform like this:
Remember the values that user make for input field and select box.
Set the default value category2 for the select box.
How could I achieve this?
try default will be cat2 and after selected will be result
<form method="post">
<Select name="field">
<Option <?php if(isset($_POST['field']) && $_POST['field'] == "category1") echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
<Option <?php if ((isset($_POST['field']) && $_POST['field'] == "category2") OR empty($_POST['field'])) echo 'selected="selected'; ?> VALUE="category2" >category2</option>
</Select>
<input type="submit" />
</form>
u may use like this
<form method="post">
<Select name="field">
<Option VALUE="category2" >category2</option>
<Option <?php if($_POST['field'] == "category1") echo 'selected="selected"'; ?> VALUE="category1" >category1</option>
<Option <?php if($_POST['field'] == "category3") echo 'selected="selected"'; ?> VALUE="category3" >category3</option>
</Select>
<input type="submit" />
</form>

PHP form values after POST in dropdown

I have a form with 'selected' values pulled from the database.
Now I want the user to edit the values.
When the data is send I want to show the new values.
When I submit my form I always get the 'green' value?
What am I doing wrong here?
<?php
// pulled from db
$color = "blue";
// update
if (isset($_POST['Submit'])) {
echo "write to db: " . $_POST['name'] . " + " . $_POST['color'];
}
?>
<html>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label>
<input type="text" name="name" size="30" value="<?php echo (isset($_POST['name'])) ? $_POST['name'] : ""; ?>">
<br />
<label for="color">Color:</label>
<select name="color">
<option <?php echo (isset($_POST['color']) || $color == "red") ? 'selected="selected"' : ''; ?> value="red">red</option>
<option <?php echo (isset($_POST['color']) || $color == "blue") ? 'selected="selected"' : ''; ?> value="blue">blue</option>
<option <?php echo (isset($_POST['color']) || $color == "green") ? 'selected="selected"' : ''; ?> value="green">green</option>
</select>
<br />
<input type="submit" name="Submit" value="Update">
</form>
</html>
Your conditionals all use ||. They all evaluate to TRUE when the post is set. If you look at the HTML output, every option will say selected='selected'.
Just compare $_POST['color'] to your specified string.
<option <?php echo (isset($_POST['color']) || $color == "red") ? 'selected="selected"' : ''; ?> value="red">red</option>
|| is the "or" operator. If $_POST['color'] is set (i.e., the form was submitted), that will always evaluate to true. You should probably just do
$_POST['color'] == 'red'
Instead. Forget the isset check.

Categories