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
}
?>
Related
Hi I am trying to make dropdown with default set based on php variable but not getting desired result please help I am a new into this
<?php
if ($_POST['search'] != '') {
$searchType = $_POST['search_type'];
}
?>
<form action="" method="POST">
<select name="search_type" id="search_type">
<option value='A' <?=(isset($searchType) && ($searchType=="A"))?'selected':'';?> >A</option>
<option value='1' <?=(isset($searchType) && ($searchType=="1"))??'selected';?> >1</option>
<option value='x' <?=(isset($searchType) && ($searchType=="x"))??'selected';?> >x</option>
<option value='y' <?php (isset($searchType) && ($searchType=="y"))??'selected';?> >y</option>
<option value='z' <?=(isset($searchType) && ($searchType=="z"))??'selected';?> >z</option>
</select>
<input type="text" name="search" id="search" placeholder="Search.. " >
</form>
You can save a bunch of code by creating an array of your values and looping through them. When looping through them, you can do a check if your value matches your POST data.
arr = ['A','1','x','y','z'];
foreach ($arr as $val){
if($searchType === $val){
$sel = 'selected';
} else { $sel = '';};
echo "<option value=\"".$val."\" ".$sel.">".$val."</option>";
};
I have a multiple select on my code, what I need to do is to have a validation when the user click the submit button without selecting any of the given list.
Here's the sample code:
index.php
<?php
IF(isset($_POST['Rtype'])){
$RetrieveType = $_POST['Rtype'];
IF($RetrieveType == 'date_range'){
$start_date = new DateTime($_POST['start_date']);
$sd = date_format($start_date,'Y-m-d');
$p_week=array();
$m_month=01;
$end_date = new DateTime($_POST['end_date']);
$end_date-> add(new DateInterval('P1D'));
$ed =date_format($end_date,'Y-m-d');
}
ELSEIF($RetrieveType == 'weekly'){
$p_week = $_POST['week'];
$m_week = implode(',',$p_week);
$m_month =$_POST['month_m'];
$m_year =$_POST['year_m'];
$p_lob = $_POST['lob'];
$sc_lob=implode(',',$p_lob);
} ELSE
{
$RetrieveType = 'date_range';
$sd = date('Y-m-01');
$start_date = date('Y-m-01');
$ed = date('Y-m-d');
$end_date = date('Y-m-d');
$m_month=date ('m');
$p_week=array();
$m_year= date ('Y');
$sc_lob='';
}
?>
<html>
<head>
<head>
<body>
<form action="index.php" method="POST" class="form-inline">
<label for="sel1">Week:</label>
<select data-placeholder="<?php echo (isset($_POST['week']) ? "Week/s Currently Selected: ".implode(",",$_POST['week']) : "Select Week"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "week[]">
<option value="1" id="empty">Week 1</option>
<option value="2" id="empty">Week 2</option>
<option value="3" id="empty">Week 3</option>
<option value="4" id="empty">Week 4</option>
<option value="5" id="empty">Week 5</option>
</select>
<label for="sel1">LOB:</label>
<select data-placeholder="<?php echo (isset($_POST['lob']) ? "LOB/s Currently Selected: ".implode(",",$_POST['lob']) : "Select LOB"); ?>"
class="chosen-select" multiple tabindex="4" style="width:350px;" name= "lob[]">
<?php
$lob = array();
$q = "SELECT distinct LOB from roster where EmployStatus='active' and SDLead <> '' group by LOB";
$params = array();
$query = sqlsrv_query($conn, $q);
while($rowsss= sqlsrv_fetch_array($query)) {
$lob = $rowsss['LOB'];
echo "<option value='".$lob."'>".$lob."</option>";
}
for ($i = 0; $i <= count($lob) - 1; $i++) {
IF($sc_lob == $lob[$i])
{$isSelected = 'selected';}
elseif(1==1)
{$isSelected='';}
echo "<option ".$isSelected." value='".$lob[$i]."'>".$lob[$i]."</option>"; }
?>
<input type="hidden" name="Rtype" value="weekly">
<input class="btn btn-primary" type="submit" />
</form>
What I wanted to achieve is when the user clicked the submit button without selecting any on the "Week" list or "LOB" list, there would be an error message that says "This field is required, select at least one.". Actually I already did this before, when I'm just using a checkbox. I placed the code below after the label tag:
sample code:
<?php
if(isset($_GET['err']))
{
$err = $_GET['err'];
if($err == 1)
{
echo "<span class='text-danger'>* This field is required, select at least one.</span>";
}
else
{
echo "";
}
}
else
{
echo "";
}
?>
Try this
if(isset($_POST['submit']){
errors = 0;
if($_POST['nameOfSelect'] == ""){
errors++;
}
if(errors == 0){
return true;
}else{
return false;
}
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>
I have started with PHP and HTML and would like to execute simple code with three drop-down lists (select tag). But when I make selection from one, the other two selected values disappear. Should I save values when submitting them and then echo. If yes, how can I do it. Sample code will be appreciated.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))$name_vid=($_POST['vid']);
else $name_vid="no";
if (isset($_POST['type']))$name_type=sanitizeString($_POST['type']);
else $name_type="no";
if (isset($_POST['model']))$name_model=sanitizeString($_POST['model']);
else $name_model="no";
echo <<<_END
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option value = "apple">apple</option>
<option value = "cherry">cherry</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="type" size="1">
<option value="" selected>Color</option>
<option value = "green">green</option>
<option value = "red">red</option>
<option value = "orange">orange</option>
</select>
<input type="submit"/><br />
<select name="model" size="1">
<option value="" selected>Model</option>
<option value = "1-a">1-a</option>
<option value = "2-b">2-b</option>
<option value = "3-c">3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
_END;
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I think you need to re-select the values of the drop downs after submission. The following code would be a fix.
<?php // formtest_2.php
$name_vid = $name_type = $name_model = "(nothing)";
if (isset($_POST['vid']) && $_POST['vid']) $name_vid=($_POST['vid']);
if (isset($_POST['type']) && $_POST['type']) $name_type=sanitizeString($_POST['type']);
if (isset($_POST['model']) && $_POST['model']) $name_model=sanitizeString($_POST['model']);
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="">Product</option>
<option value = "apple" <?php if($name_vid == 'apple') echo 'selected="selected"'; ?>>apple</option>
<option value = "cherry" <?php if($name_vid == 'cherry') echo 'selected="selected"'; ?>>cherry</option>
<option value = "orange" <?php if($name_vid == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="type" size="1">
<option value="">Color</option>
<option value = "green" <?php if($name_type == 'green') echo 'selected="selected"'; ?>>green</option>
<option value = "red" <?php if($name_type == 'red') echo 'selected="selected"'; ?>>red</option>
<option value = "orange" <?php if($name_type == 'orange') echo 'selected="selected"'; ?>>orange</option>
</select>
<br />
<select name="model" size="1">
<option value="">Model</option>
<option value = "1-a" <?php if($name_model == '1-a') echo 'selected="selected"'; ?>>1-a</option>
<option value = "2-b" <?php if($name_model == '2-b') echo 'selected="selected"'; ?>>2-b</option>
<option value = "3-c" <?php if($name_model == '3-c') echo 'selected="selected"'; ?>>3-c</option>
</select>
<input type="submit"/><br />
</form>
</body>
</html>
<?php
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I would not use heredoc syntax ("<<<") to print HTML.
Try this out, i made one submit button, and re selected the values after submit :
<?php
// formtest_2.php
$name_vid = $name_type = $name_model = "";
if (isset($_POST['vid']))
$name_vid = ($_POST['vid']);
else
$name_vid = "no";
if (isset($_POST['type']))
$name_type = sanitizeString($_POST['type']);
else
$name_type = "no";
if (isset($_POST['model']))
$name_model = sanitizeString($_POST['model']);
else
$name_model = "no";
///////////////////
if($name_vid == 'apple')
{
$v1 = 'selected';
}
elseif($name_vid == 'cherry')
{
$v2 = 'selected';
}
elseif($name_vid == 'orange')
{
$v3='selected';
}
////////////////////////
if($name_type == 'green')
{
$t1 = 'selected';
}
elseif($name_type == 'red')
{
$t2 = 'selected';
}
elseif($name_type == 'orange')
{
$t3='selected';
}
///////////////////////
if($name_model == '1-a')
{
$m1 = 'selected';
}
elseif($name_model == '2-b')
{
$m2 = 'selected';
}
elseif($name_model == '3-c')
{
$m3='selected';
}
?>
<html>
<head>
<title>Form Test Two</title>
</head>
<body>
Make your selection:
<form name="fruite_form" action="formtest_2.php" method="post">
<select name="vid" size="1">
<option value="" selected>Product</option>
<option <?=$v1?> value = "apple">apple</option>
<option <?=$v2?> value = "cherry">cherry</option>
<option <?=$v3?> value = "orange">orange</option>
</select>
<select name="type" size="1">
<option value="" selected>Color</option>
<option <?=$t1?> value = "green">green</option>
<option <?=$t2?>value = "red">red</option>
<option <?=$t3?>value = "orange">orange</option>
</select>
<select name="model" size="1">
<option value="" selected>Model</option>
<option <?=$m1?> value = "1-a">1-a</option>
<option <?=$m2?>value = "2-b">2-b</option>
<option <?=$m3?>value = "3-c">3-c</option>
</select>
<input name="submitButtom" id="submitButton" type="submit"/><br />
</form>
</body>
</html>
<?
echo "Your selection is: $name_vid and $name_type and $name_model";
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
Feel free top add back your submit buttons.
But give each a unique name and also don't forget to name your form, and as a good practice, give then an id too which will be the same as name attribute.
Update: Just to make sure you are really getting a post, since this is your initial question, print this at the end of your code
echo $_POST['vid'] . ' ' . $_POST['type'] . ' ' . $_POST['model'] . '<br/><br/>';
and see if post really holds the value after submission, if you get a value from post, but not from your assigned variables, then check your conditions used at the top to assign your values.
// you need to check if post isset and has an actual value, only than, the varibale should be assigned. Just like what Sithu said.
Once submitted selected option, the data is not stored.
just want to know how to post back the data if validation fails
The following line doesnt really work for me.
<select id="numbers" name="numbers" value="<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : " "; ?>"/>
if someone could give me a hand?
Many thanks, here is my code
<?php
if(isset($_POST['numbers']) &&($_POST['fruits']) && $_POST['numbers'] != "null" && $_POST['fruits'] !== "null")
{
echo "Thank you!";
} elseif (isset($_POST['numbers']) && $_POST['numbers'] = "null") {
echo "you forgot to choose a number";
}
elseif(isset($_POST['fruits']) && $_POST['fruits'] = "null")
{
echo "you forgot to choose fruit name";
}
?>
<form id="form" name="form" method="post" action="">
<label for="expiry">Select</label>
<select id="numbers" name="numbers" value="<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : " "; ?>"/>
<option value="null" selected="selected">-</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
</select>
<select id="fruits" name="fruits" value="<?php echo (isset($_POST['fruits']))? $_POST['fruits'] : ''; ?>"/>
<option value="null" selected="selected">-</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Pear">Pear</option>
</select>
<input type="submit" value="Send" />
</form>
Solved it, Maybe not a best way, but at least got it sorted:
<?php
$item = null; #
$itemyear = null;
if(isset($_POST['numbers'])){
$item = $_POST['numbers'];
}
if(isset($_POST['fruits'])){
$itemyear = $_POST['fruits'];
}
if(isset($item) && isset($itemyear) && $item != "null" && $itemyear !== "null")
{
echo "Thank you!";
} elseif ($item == "null") {
echo "you forgot to choose a number";
}
elseif($itemyear == "null")
{
echo "you forgot to choose fruit name";
}
?>
<form id="form" name="form" method="post" action="">
<label for="expiry">Select</label>
<select id="numbers" name="numbers" />
<option value="null" selected="selected">-</option>
<option value="01" <?php if($item == '01'): echo "selected='selected'"; endif; ?>>01</option>
<option value="02" <?php if($item == '02'): echo "selected='selected'"; endif; ?>>02</option>
<option value="03" <?php if($item == '03'): echo "selected='selected'"; endif; ?>>03</option>
</select>
<select id="fruits" name="fruits" />
<option value="null" selected="selected">-</option>
<option value="Apple"<?php if($itemyear == 'Apple'): echo "selected='selected'"; endif; ?> >Apple</option>
<option value="Banana"<?php if($itemyear == 'Banana'): echo "selected='selected'"; endif; ?>>Banana</option>
<option value="Pear"<?php if($itemyear == 'Pear'): echo "selected='selected'"; endif; ?>>Pear</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
echo $item ."-". $itemyear;
?>
the PHP isset() function returns either true or false (depending on whether the input is.. well... set.
You would want to use this:
value='<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : ""; ?>
You can't set a value attribute on a <select>. You have to find the correct <option> and set its selected attribute. Personally, I put a data-default attribute on the <select> and then use JavaScript to loop through the options and find the right one.
Oh now I see.
I don't know what the usual thing to do is but one way is to put all the data as a query string when you redirect the user back. The reason why it doesn't stay in the $_POST global is because it's only kept on the page you post to then it's gone.
So when you redirect the user back
if(validationFailed)
{
header("Location: page.php?data=example");
}
The data can then be retrieved in page.php by using
$data = $_GET['data']; // contains "example"