I'm making a calculator similar to This Calculator
But instead of using Javascript I'm using only HTML and PHP without any kind of scripting, not even CSS.
What happened is that there are 4 text boxes and depending on the choice from the dropdown menu, every time one of those is left empty because the answer will be output which should be in that textbox but I'm echoing the answer and want to disable the box whose value is not needed at that time.
Any help would be appreciated and I know it's a very lousy code but for the time being I just want to add what I described:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Aluminum Pipe - Pressure Rating Calculation </title>
</head>
<body>
<form action="AlPipe.php" method="post">
<div id="new" align="center">
<h2 align="center">Ordering Decimals from Least to Greatest</h2>
<select name="new" align="center">
<option align="center" value="P">Pressure Rating (PR)</option>
<option align="center" value="S">Allowable Stress (S) </option>
<option align="center" value="T">Wall Thickness(T)</option>
<option align="center" value="D">Pipe Outside Diameter(D)</option>
</select>
<p align="center">Allowable Stress(S) =
<input type="text" name="AL" size="5" />
</p>
<p align="center"> Wall Thickness(t) =
<input type="text" name="WT" size="5" />
</p>
<p align="center">Pipe Outside Diameter(D) =
<input type="text" name="POD" size="5"/>
</p>
<p align="center">Pressure Rating(PR) =
<input type="text" name="PR" size="5" />
</p>
<div align="center">
<input type=submit value=Calculate name="Calculate">
<input type=reset value=Reset>
<?php
formula();
function formula()
{
if(isset($_POST['Calculate']))
{
$S=$_POST['AL'];
$T=$_POST['WT'];
$D=$_POST['POD'];
$P=$_POST['PR'];
$cal=$_POST['new'];
}
if($cal=='P')
{
$PR1 = (2 * $S * $T );
$PR2 = $D;
$PR3 = $PR1 / $PR2;
echo "\n Pressure Rating is : ".$PR3;
}
elseif($cal=='S')
{
$S1= ($P * $D) ;
$S2= ($T * 2);
$S3= $S1 / $S2;
echo "\n Allowable Stress is : ".$S3;
}
elseif($cal=='T')
{
$T1 = $P * $D ;
$T2 = 2 * $S;
$T3 = $T1 / $T2;
echo "\nWall Thickness is : ".$T3;
}
elseif($cal=='D')
{
$D1 = 2 * $S * $T / $P ;
echo "\nDiameter is : ".$D1;
}
else
{
echo "Invalid Values";
}
}
?>
</div>
</form>
</div>
</div>
</body>
Does the field need to be disabled after the submit or based on the drop down? Either way you can make the form submit to php and then use something like the following to inject the disabled keyword into your calculator for example you could have a drop down box that has an update button next to it that does the same thing as what follows with the exception it uses the post data from the dropdown to determine what to disable.
<!-- language: lang-php -->
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Aluminum Pipe - Pressure Rating Calculation
</title>
</head>
<body>
<form method="post">
<div id="new" align="center">
<h2 align="center">
Ordering Decimals from Least to Greatest
</h2>
<select name="new" align="center">
<option align="center" value="P">Pressure Rating (PR)</option>
<option align="center" value="S">Allowable Stress (S) </option>
<option align="center" value="T">Wall Thickness(T)</option>
<option align="center" value="D">Pipe Outside Diameter(D)</option>
</select>
<p align="center">
Allowable Stress(S) =
<input type="text" name="AL" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['AL']) && $_POST['WT'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Wall Thickness(t) =
<input type="text" name="WT" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['WT']) && $_POST['WT'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Pipe Outside Diameter(D) =
<input type="text" name="POD" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['POD']) && $_POST['POD'] == '')) ? 'disabled' : ''; ?> />
</p>
<p align="center">
Pressure Rating(PR) =
<input type="text" name="PR" size="5" <?= (isset($_POST['Calculate']) && (isset($_POST['PR']) && $_POST['PR'] == '')) ? 'disabled' : ''; ?> />
</p>
<div align="center">
<input type=submit value=Calculate name="Calculate">
<input type=reset value=Reset>
</div>
</form>
</div>
</div>
</body>
<?php
formula();
function formula()
{
if(isset($_POST['Calculate']))
{
$S=$_POST['AL'];
$T=$_POST['WT'];
$D=$_POST['POD'];
$P=$_POST['PR'];
$cal=$_POST['new'];
}
if($cal=='P')
{
$PR1 = (2 * $S * $T );
$PR2 = $D;
$PR3 = $PR1 / $PR2;
echo "\n Pressure Rating is : ".$PR3;
}
elseif($cal=='S')
{
$S1= ($P * $D) ;
$S2= ($T * 2);
$S3= $S1 / $S2;
echo "\n Allowable Stress is : ".$S3;
}
elseif($cal=='T')
{
$T1 = $P * $D ;
$T2 = 2 * $S;
$T3 = $T1 / $T2;
echo "\nWall Thickness is : ".$T3;
}
elseif($cal=='D')
{
$D1 = 2 * $S * $T / $P ;
echo "\nDiameter is : ".$D1;
}
else
{
echo "Invalid Values";
}
}
?>
Related
I'm a student doing a challenge where I would have to make a Calculator-type form where you can input two values and click an operation. It's a simple concept using only 4 operations.
I was able to make the format of the form: title, input text and buttons. But I can't find a way to take the input information and manipulating the information. My initial goal was to take the two values and adding/subtracting/multiplying/dividing the values and printing the statement above.
For example:
1 + 2 = 3 //statement printed above
First Value: 1
Second Value: 2 //insert values
+ - * / //click operation buttons
Any suggestions?
<!DOCTYPE HTML>
<?php
print_r($_POST);
if ( isset($_POST["+"]) ) {
$sum = $var1 + $var2;
echo "$var1 + $var2 = $sum";
}
elseif( isset($_POST["-"]) ) {
$sum = $var1 - $var2;
echo "$var1 - $var2 = $sum";
}
elseif ( isset($_POST["*"]) ) {
$sum = $var1 * $var2;
echo "$var1 * $var2 = $sum";
}
elseif ( isset($_POST["/"]) ) {
$sum = $var1 / $var2;
echo "$var1 / $var2 = $sum";
}
?>
<html>
<body>
<form action="" method="POST">
First Value: <input type="text" name="First Value"><br><br>
Second Value: <input type="text" name="Second Value"><br><br>
Operations: <button type="submit" name "+">+</button>
<button type="submit" name "-">-</button>
<button type="submit" name "*">*</button>
<button type="submit" name "/">/</button>
</form>
</body>
</html>
This seems to fix the errors I mentioned in comments
<!DOCTYPE HTML>
<html>
<body>
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST'){
if ( isset($_POST["+"]) ) {
$sum = $_POST['var1'] + $_POST['var2'];
echo "$_POST[var1] + $_POST[var2] = $sum";
}
elseif( isset($_POST["-"]) ) {
$sum = $_POST['var1'] - $_POST['var2'];
echo "$_POST[var1] - $_POST[var2] = $sum";
}
elseif ( isset($_POST["*"]) ) {
$sum = $_POST['var1'] * $_POST['var2'];
echo "$_POST[var1] * $_POST[var2] = $sum";
}
elseif ( isset($_POST["/"]) ) {
$sum = $_POST['var1'] / $_POST['var2'];
echo "$_POST[var1] / $_POST[var2] = $sum";
}
}
?>
<form action="" method="POST">
First Value: <input type="text" name="var1"><br><br>
Second Value: <input type="text" name="var2"><br><br>
Operations: <button type="submit" name="+">+</button>
<button type="submit" name="-">-</button>
<button type="submit" name="*">*</button>
<button type="submit" name="/">/</button>
</form>
</body>
</html>
I don't know if it's the right way to do things but you can use jquery in the script section to do so, let's say you have this form
<form id="target" action="destination.html">
<input type="text" value="Hello there">
<input type="submit" value="Go">
</form>
so on the submit you do the math
$( "#target" ).submit(function( event ) {
//do the math//
document.write(//your answer//);
event.preventDefault();
});
<?php
$first_num = $_POST['first_num'];
$second_num = $_POST['second_num'];
$operator = $_POST['operator'];
$result = '';
if (is_numeric($first_num) && is_numeric($second_num)) {
switch ($operator) {
case "Add":
$result = $first_num + $second_num;
break;
case "Subtract":
$result = $first_num - $second_num;
break;
case "Multiply":
$result = $first_num * $second_num;
break;
case "Divide":
$result = $first_num / $second_num;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="page-wrap">
<h1>Simple Calculator Program</h1>
<form action="" method="post" id="quiz-form">
<p>
<label>First Number</label>
<input type="number" name="first_num" id="first_num" required="required" value="<?php echo $first_num; ?>" />
</p>
<p>
<label>Second Number</label>
<input type="number" name="second_num" id="second_num" required="required" value="<?php echo $second_num; ?>" />
</p>
<p>
<label>Result</label>
<input readonly="readonly" name="result" value="<?php echo $result; ?>">
</p>
<input type="submit" name="operator" value="Add" />
<input type="submit" name="operator" value="Subtract" />
<input type="submit" name="operator" value="Multiply" />
<input type="submit" name="operator" value="Divide" />
</form>
</div>
</body>
</html>
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
}
?>
I have been working on a form that allows entering a menu item for a cafe establishment, alongside its ingredients (arrays of data). Unfortunately, a problem came up as it only executes 1 query even though 2 or more ingredients were entered in the form (dynamic, jQuery).
Here is the PHP code:
<?php
include("session.php");
if (isset($_POST['submit'])) {
$productname = $_POST['product_name'];
$categoryID = $_POST['categoryID'];
$price = $_POST['srp'];
// ingredients
$ingredients = $_POST['ingredients'];
$qty = $_POST['qty'];
$measure = $_POST['measure'];
if (!empty($productname) && !empty($categoryID) && !empty($price) && !empty($ingredients) && !empty($qty) && !empty($measure)) {
for ($i=0; $i < count($ingredients); $i++) {
if ($ingredients[$i] != "" && $qty[$i] != "" && $measure[$i] != "") {
mysqli_query($db, "insert into individual_ingredients values ('', '$productname', '{$ingredients[$i]}', '{$qty[$i]}', '{$measure[$i]}')");
}
}
mysqli_query($db, "insert into end_products values ('', '$productname', '$price', '', '$categoryID')");
mysqli_query($db, "insert into audit_trail values ('', now(), '{$_SESSION['login_user']}', 'New end product added')");
header("location: end_products.php");
} else {
echo '<font color="red">'."Incomplete data entered".'</font>';
}
}
?>
And here is the HTML form and JQuery:
<html>
<head>
<title><?php echo $login_session; ?> | New End Product Record</title>
<link rel="stylesheet" href="css/main.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Bootstrap js library -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//add more fields group
$(".addMore").click(function(){
var fieldHTML = '<div class="form-group fieldGroup">'+$(".fieldGroupCopy").html()+'</div>';
$('body').find('.fieldGroup:last').after(fieldHTML);
});
//remove fields group
$("body").on("click",".remove",function(){
$(this).parents(".fieldGroup").remove();
});
});
</script>
</head>
<body>
HTML form:
<table style="margin: 5% -1% 0 -10%; font-size: 0.9em">
<tr>
<form action="new_end_product_record.php" method="post">
<td>Name</td>
<td><input type="text" name="product_name"></td>
<td>Raw Material/s Used</td>
<td>
<div class="fieldGroup">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
ADD
<br /><br />
</div>
<!-- second set -->
<div class="fieldGroupCopy" style="display: none;">
<div class="input-group">
<select name="ingredients[]">
<option value="">Ingredient</option>
<?php
$items_sql = "select name from raw_materials where status='Active'";
$get_items = mysqli_query($db, $items_sql);
while ($option = mysqli_fetch_assoc($get_items)) { ?>
<option value="<?php echo $option['name']; ?>"><?php echo $option['name']; ?></option>
<?php } ?>
</select>
<input type="text" name="qty[]" placeholder="Quantity" style="width:60px">
<select name="measure[]">
<option value="">Measure Unit</option>
<?php
$get_units = "select * from raw_material_measures";
$units = mysqli_query($db, $get_units);
while ($unit = mysqli_fetch_assoc($units)) {
?>
<option value="<?php echo $unit['full_name']; ?>"><?php echo $unit['full_name']; ?></option>
<?php } ?>
</select>
REMOVE
<br /><br />
</div>
</div>
</td>
</tr>
<tr>
<td>SRP</td>
<td><input type="text" name="srp"></td>
</tr>
<tr>
<td>Category</td>
<td>
<select name="categoryID">
<option value="">Select category...</option>
<!--list all categories in the database-->
<?php
$cat_query = "select category_ID, name from end_products_categories";
$get_cats = mysqli_query($db, $cat_query);
while ($option = mysqli_fetch_assoc($get_cats)) { ?>
<option value="<?php echo $option['category_ID']; ?>"><?php echo $option['name']?></option>
<?php } ?>
</select>
</td>
<!-- <td>Expiration</td>
<td><input type="date"></input></td> -->
</tr>
</table><br>
<input type="submit" class="button" name="submit" value="ADD RECORD">
<input type="reset" value="ERASE ALL">
</div></form>
</div>
</body>
</html>
Is there a problem with the loop or with the HTML form that prevents the second to the last set of values from being inserted? Any help would be appreciated.
I am struggling to get my PHP unit converter to work.
I am trying to get multiple converters going but cant seem to get it working.
It'd be great if someone could show me where I'm going wrong and help me get it going. :)
<?php
if($_POST){
$fahrenheit = $_POST['fahrenheit'];
$celsius = ($fahrenheit - 32)*5/9;
}
if($_POST){
$celsius = $_POST['celcius'];
$fahrenheit = ($celcius - 32)*5/9;
}
?>
<form action="" method="post">
Fahrenheit: <input type="text" name="fahrenheit" /><br />
<?php
if(isset($celsius)){
echo "Celsius = ".$celsius;
}
?>
</form>
<?php
function fahrenheit_to_celsius($given_value)
{
$celsius=5/9*($given_value-32);
return $celsius ;
}
function celsius_to_fahrenheit($given_value)
{
$fahrenheit=$given_value*9/5+32;
return $fahrenheit ;
}
function inches_to_centimeter($given_value)
{
$centimeter=$given_value/2.54;
return $centimeter ;
}
function centimeter_to_inches($given_value)
{
$inches=$given_value*2.54
}
?>
<html>
<head>
<title>Temp. Conv.</title>
</head>
<body>
<form action="" method="post">
<table>
<!-- FAHRENHEIGHT & CELCIUS V -->
<tr>
<td>
<select name="first_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_temp_type_name">
<option value="fahrenheit">Fahrenheit</option>
<option value="celsius">Celsius</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="btn" value="Convert">
</td>
</tr>
<!--FAHRENHEIGHT & CELCIUS ^ -->
<!-- CENTEMETERS & INCHES -->
<tr>
<td>
<select name="first_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<tr>
<td>
<select name="second_length_type_name">
<option value="centimeter">centimeter</option>
<option value="inches">Inches</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" name="given_value">
</td>
</tr>
<!--CENTEMETERS & INCHES ^-->
<tr>
<td>
<?php
if(isset($_POST['btn']))
{
$first_temp_type_name=$_POST['first_temp_type_name'];
$second_temp_type_name=$_POST['second_temp_type_name'];
$given_value=$_POST['given_value'];
if($first_temp_type_name=='fahrenheit')
{
$celsious=fahrenheit_to_celsius($given_value);
echo "Fahrenheit $given_value = $celsious Celsious";
}
if($first_temp_type_name=='celsius')
{
$fahrenheit=celsius_to_fahrenheit($given_value);
echo "Celsious $given_value = $fahrenheit Fahrenheit";
}
}
if(isset($_POST['btn']))
{
$first_length_type_name=$_POST['first_length_type_name'];
$second_length_type_name=$_POST['second_length_type_name'];
$given_value=$_POST['given_value'];
if($first_length_type_name=='centimeter')
{
$centimeter=centimeter_to_inches($given_value);
echo "Centimeter $given_value = $inches Inches";
}
if($first_length_type_name=='inches')
{
$centimeter=inches_to_centimeter($given_value);
echo "Inches $given_value = $centimeter centimeter";
}
}
?>
</td>
</tr>
</table>
</form>
</body>
</html>
I know there is a lot going on, my apologies.
Any help is greatly appreciated :)
Hi please use the following code.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$convertedTemperature = 0;
/* The condition is entered when the request is of POST type. */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$temperature = $_POST['temperature'];
$fromConvertionUnit = $_POST['fromConvertionUnit'];
$toConvertionUnit = $_POST['toConvertionUnit'];
/* if the temperature conversion are of same unit then no need for conversion */
if($fromConvertionUnit == $toConvertionUnit){
$convertedTemperature = $temperature;
}else if($fromConvertionUnit == 'fahrenheit' && $toConvertionUnit == 'celcius') {
/* formula to convert Fahrenheit to Celcius */
$convertedTemperature = ($temperature - 32) * 0.5556;
}else if($fromConvertionUnit == 'celcius' && $toConvertionUnit == 'fahrenheit') {
/* formula to convert Celcius to Fahrenheit */
$convertedTemperature = ($temperature * 1.8) + 32;
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temperature Converter</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div>
<!-- If the temperature value has be submitted and has data then it will prefilled -->
<label for="temperature">Temperature</label> <br/>
<input type="number" name="temperature" id="temperature" value="<?php echo (!empty($temperature)) ? $temperature : '' ?>">
</div>
<div>
<label for="fromConvertionUnit">Select From Convertion Unit</label><br/>
<select name="fromConvertionUnit" id="fromConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<div>
<label for="toConvertionUnit">Select To Convertion Unit</label><br/>
<select name="toConvertionUnit" id="toConvertionUnit">
<option value="fahrenheit">Fahrenheit</option>
<option value="celcius">Celcius</option>
</select>
</div>
<!-- Once the page is submitted and conversion is done the respective values will be added in the following section -->
<div>
Converted Temperature <b> <?php echo (!empty($temperature)) ? $temperature : '--' ?></b> Value From <b><?php echo (!empty($fromConvertionUnit)) ? $fromConvertionUnit : '--' ?></b> TO <b><?php echo (!empty($toConvertionUnit)) ? $toConvertionUnit : '--' ?></b> is <b><?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '--' ?><b/>
<label for="converted_value">Converted Value</label><br/>
<input type="number" value="<?php echo (!empty($convertedTemperature)) ? $convertedTemperature : '0' ?>">
</div>
<div>
<input type="submit" value="Convert">
</div>
</form>
</body>
</html>
If you want to make a converter, all you need is one input - and a dropdown between what you wish to convert to. Then use a switch in PHP when the form was submitted to check what function you wish to use.
Your current issue is that you overwrite a lot of values, and that you don't check for the right buttons. This is also over-complicating it.
You can further develop this converter by making sure that the input is an actual number - by using filter_var() with a flag that's suitable for your need. You can either validate it or sanitize it, see FILTER_SANITIZE vs FILTER VALIDATE, whats the difference - and which to use?.
<?php
if (isset($_POST['submit'])) {
switch ($_POST['convert']) {
case "cm-in":
$result = centimeter_to_inches($_POST['value']);
$old_unit = 'cm';
$new_unit = ' inches';
break;
case "in-cm":
$result = inches_to_centimeter($_POST['value']);
$old_unit = ' inches';
$new_unit = 'cm';
break;
case "f-c":
$result = fahrenheit_to_celsius($_POST['value']);
$old_unit = ' Farenheit';
$new_unit = ' Celcius';
break;
case "c-f":
$result = celsius_to_fahrenheit($_POST['value']);
$old_unit = ' Celcius';
$new_unit = ' Farenheit';
break;
}
}
function fahrenheit_to_celsius($given_value) {
return 5/9*($given_value-32);
}
function celsius_to_fahrenheit($given_value) {
return $given_value*9/5+32;
}
function inches_to_centimeter($given_value) {
return $given_value/2.54;
}
function centimeter_to_inches($given_value) {
return $given_value*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Conversions</title>
</head>
<body>
<form method="post">
Convert <input type="text" name="value" /><br />
<select name="convert">
<option value="">--Select one--</option>
<optgroup label="Units of Length">
<option value="cm-in">Centimeter to inches</option>
<option value="in-cm">Inches to centimeter</option>
</optgroup>
<optgroup label="Units of Temperature">
<option value="f-c">Farenheit to Celcius</option>
<option value="c-f">Celcius to Farenheit</option>
</optgroup>
</select>
<input type="submit" name="submit" value="Convert" />
</form>
<?php
if (!empty($result))
echo '<p>'.$_POST['value'].$old_unit.' equals '.$result.$new_unit.'</p>';
?>
</body>
</html>
I'm writing a php form and I can't get the drop down boxes and check boxes to stick as in when I fill in my details but don't click something it will keep everything else filled but that one part that wasn't filled out. I can do it for the input text and radio buttons but I can't get it done for drop downs and checkboxes
<!DOCTYPE html>
<style>
#import url(stickyTextInput.css);
</style>
<?php
if(isset($_REQUEST["left"]))
{
process_form();
}
else
{
display_form_page('');
}
?>
<?php
function display_form_page($error)
{
$self =$_SERVER['PHP_SELF'];
$first_name = isset($_REQUEST['name']) ? $_REQUEST['name']:'';
$last_name = isset($_REQUEST['lastname']) ? $_REQUEST['lastname']:'';
$age = isset($_REQUEST['age']) ? $_REQUEST['age']:'';
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']: '';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head>
<title>
Forms Sticky input
</title>
<style>
#import url(stickyTextInput.css);
</style>
<style type="text/css">
.error
{
color:#ff0000
}
</style>
</head>
<body>
<?php
if($error)
{
echo "<p>$error</p>\n";
}
?>
<form action= "<?php echo $self?>" method = "post">
<h1>Forms-Sticky Input</h1>
<label>First Name:</label>
<input type="text" size="10" maxlength="40" name="name" value = "<?php echo $first_name?>">
<br>
<label>Last Name:</label>
<input type="text" size="10" maxlength="40" name="lastname" value = "<?php echo $last_name?>">
<br>
<label>Age:</label>
<input type="text" name="age" size="10" value="<?php echo $age?>">
<br>
<label>Gender</label>
<input type="radio" name="gender" value="male" <?php check($gender, "male")?>>Male
<input type="radio" name="gender" value="female" <?php check ($gender, "female")?>>Female
<br>
<label>Select favourite Colour</label>
<select name= "color">
<option <?php checkradio($color, "Red")?>>Red
<option <?php checkradio($color, "Blue")?>>Blue
<option <?php checkradio($color, "Green")?>>Green
<option <?php checkradio($color, "Pink")?>>Pink
<option selected="selected" disabled="disabled">
</select>
<br>
<label>Food</label>
<input type="checkbox" name="food[]" value="beans" <?php checkbox ($food, "beans")?>>Beans
<input type="checkbox" name="food[]" value="crisps" <?php checkbox ($food, "crisps")?>>Crisps
<input type="checkbox" name="food[]" value="lemons" <?php checkbox ($food, "lemons")?>>Lemons
<br>
<div id="buttons">
<input type="submit" name="left" id="left" value="Submit" >
<input type="reset" name="right" id="right" value="Reset" >
</div>
</form>
</body>
</html>
<?php
}
?>
<?php
// If $group has the value $val then select this list item
function check($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function checkradio($group, $val)
{
if ($group === $val)
{
echo 'selected = "selected"';
}
}
?>
<?php
// If $group has the value $val then select this list item
function checkbox($group, $val)
{
if ($group === $val)
{
echo 'checked = "checked"';
}
}
?>
<?php
function process_form()
{
$error = validate_form();
if($error)
{
display_form_page($error);
}
else
{
display_output_page();
}
}
?>
<?php
function validate_form()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
$error = '';
$reg_exp = '/^[a-zA-Z\-\']+$/';
$reg_exp1 = '[0-9]{3}';
if(!preg_match($reg_exp, $first_name))
{
$error .= "<span class=\"error\">First Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!preg_match($reg_exp, $last_name))
{
$error .= "<span class=\"error\">Last Name is invalid (letters, hyphens, ', only)</span><br>";
}
if (!is_numeric($age))
{
$error .= "<span class=\"error\">Age is invalid (numbers only)</span><br>";
}
if (strlen($gender) == 0)
{
$error .= "<span class=\"error\">Select Male/Female</span><br>";
}
if (strlen($color) == 0)
{
$error .= "<span class=\"error\">Select one color</span><br>";
}
if (! is_array($food))
{
$error .= "<span class=\"error\">You must select one food</span><br>";
}
return $error;
}
?>
<?php
function display_output_page()
{
$first_name = trim($_REQUEST['name']);
$last_name = trim($_REQUEST['lastname']);
$age = trim($_REQUEST['age']);
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender']:'';
$color = isset($_REQUEST['color']) ? $_REQUEST['color']:'';
$food = isset($_REQUEST['food']) ? $_REQUEST['food']:'';
?>
<html>
<head><title>Form Results</title></head>
<body>
<h1>Form Results</h1>
<?php
echo " First Name: $first_name<br/>\n";
echo " Last Name: $last_name<br/>\n";
echo " Age: $age<br/>\n";
echo " Gender: $gender<br/>\n";
echo " Favourite Color: $color<br/>\n";
echo "<ul>";
if (is_array($food))
{
echo "Favourite Food is:";
foreach($food as $selection)
{
echo "<li>$selection</li>";
}
}
echo "</ul>";
?>
</body>
</html>
<?php
}
?>
Possibly a browser issue, however most browsers only require 'checked' at the end of the html input element for checkboxes. However you appear to be outputting checked = "checked" This is possibly the problem. Have a look at the sample below:
<?php
$name = isset($_GET['name']) ? $_GET['name'] : '';
$agree = isset($_GET['agree']) ? 'checked' : '';
$title = isset($_GET['title']) ? $_GET['title'] : '';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="">
<input type="text" name="name" id="name" value="<?=$name;?>">
<input type="checkbox" name="agree" id="agree" <?=$agree;?>>
<select name="title" id="title">
<option value="Mr" <?=$title == 'Mr' ? 'selected' : ''?>>Mr</option>
<option value="Mrs" <?=$title == 'Mrs' ? 'selected' : ''?>>Mrs</option>
<option value="Miss" <?=$title == 'Miss' ? 'selected' : ''?>>Miss</option>
</select>
<button type="submit">submit</button>
</form>
</body>
</html>
After processing the values the output html should be as follows:
<form action="">
<input type="text" name="name" id="name" value="test">
<input type="checkbox" name="agree" id="agree" checked>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss" selected>Miss</option>
</select>
<button type="submit">submit</button>
</form>