Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

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

  1. Open calculator.php (refer to Script 3.5) in your text editor.
  2. 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>
    
    03fig15.jpg

    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).

  3. 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>
    
  4. Save the file as calculator.php, upload to your Web server, and test in your Web browser ( Figures 3.10 and 3.11 ).
    03fig16.gif

    Figure 3.10 The form now recalls the previously submitted values…

    03fig17.gif

    Figure 3.11 …whether or not the form was completely filled out.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus