In Forms pt.2 we made a tool that converted kilometers to miles. In this section, we will make a tool that will accept several different kinds of units and output several different kinds of units. To do this, we will use an if statement with isset() to make it so that the results section only show after data has been entered and if statements with the logical operator to test the both the units in and the units out that the user entered at the same time. Before we get to that though, we need a form for the user to input data into:
<form>
<input type="text" cols="5" name="num_in" />
<select name="units_in">
<option value="Miles">Miles</option>
<option value="Kilometers">Kilometers</option>
<option value="Feet">Feet</option>
<option value="Meters">Meters</option>
</select>
Convert To
<select name="units_out">
<option value="Miles">Miles</option>
<option value="Kilometers">Kilometers</option>
<option value="Feet">Feet</option>
<option value="Meters">Meters</option>
</select>
<input type="submit" /><br />
</form>
That form will submit three variables, $num_in, $units_in and units_out. Between the submit button and the tag, you can use if ( isset($num_in) ) to test if anything has been submited in the num_in text input and if there has, echo out the results:
<?
if ( isset($num_in) )
{
echo "<input type="text" cols="10" name="num_out" value="0" /><br />";
echo "$num_in $units_in = $out $units_out<br />"; }
?>
Next you have to look up all the constants you need to do the conversions and tests to see the user submited to which constant to use. For example, to convert miles to kilometers, you multiply by 1.609344 but you only want to use that when both $units_in is Miles and $units_out is Kilometers so...
<?
if ( ($units_in == "Miles") && ( $units_out == "Kilometers") )
{ $constant = 1.609344;}
?>
Add all the other conversion constants that you need and finish off with
$out = $num_in*$constant;
and you can add the whole block of code above the tag.
At this point, when you use the form the text input and menus are reset to their default settings when the results are generated. To get the number entered into the form show in the results page, add the value attribute to the text input and inside that, use PHP to echo $num_in:
<input type="text" cols="5" name="num_in" value="<? echo "$num_in"; ?>" />
To get the options in the menus to retain their values in the results, use an if statement to echo the selected attribute if that option has been selected:
<option value="Feet"<?
if ( $units_in == "Feet" )
{ echo " selected"; }
?>>Feet</option>
To see the entire source code, click here.
|
|
|