Making Sticky Forms
You've certainly come across sticky forms, even if you didn't know that's what they were called. A sticky form is simply a standard HTML form that remembers how you filled it out. This is a particularly nice feature for end users, especially if you are requiring them to resubmit a form (for instance, after filling it out incorrectly in the first place).
To preset what's entered in a text box, use its value attribute:
<input type="text" name="city" size="20" value="Innsbruck" />
To have PHP preset that value, print the appropriate variable:
<input type="text" name="city" size="20" value="<?php echo $city; ?>" />
With this in mind, I'll rewrite calculator.php so that it's sticky.
To make a sticky form
- Open calculator.php (refer to Script 3.5) in your text editor.
- Change the quantity input to read (
Script 3.6
)
<p>Quantity: <input type="text" name="quantity" size="5" maxlength="10" value="<?php if (isset($_POST['quantity'])) echo $_POST['quantity']; ?>" /></p>
Script 3.6 The calculator's form now recalls the previously entered values.
The first thing I've done here is to add the value attribute to the input. Then, I print out the value of the submitted quantity variable ($_POST['quantity']). But first I want to make sure it has a value, so I check that the variable is set. The end result for the input's value is the PHP code
<?php if (isset($_POST['quantity'])) { echo $_POST['quantity']; } ?>
which I've condensed to its most minimal form (you can omit the curly braces if you have only one statement within a conditional block).
- Repeat the process for the price and tax.
<p>Price: <input type="text" name="price" size="5" maxlength="10" value="<?php if (isset($_POST['price'])) echo $_POST['price']; ?>" /></p> <p>Tax (%): <input type="text" name="tax" size="5" maxlength="10" value="<?php if (isset($_POST ['tax'])) echo $_POST['tax']; ?>" /></p>
- Save the file as calculator.php, upload to your Web server, and test in your Web browser (
Figures 3.10
and
3.11
).
Figure 3.10 The form now recalls the previously submitted values…
Figure 3.11 …whether or not the form was completely filled out.