9.21. Preventing Changes to Fields

There are two ways to display information in form fields without allowing a user to change the data: by setting the field to read only or by disabling the field.

You can add the readonly attribute to text fields to keep the user from being able to edit the data contained therein. This method has the advantage of displaying the data in field form while prohibiting the user from being able to modify it.

The disabled attribute causes the corresponding field to appear as disabled (usually graying out the control, consistent with the user agent's platform method of showing disabled controls) so the user cannot use the control.

The following code shows examples of both a read-only and a disabled control. The output of this code is shown in Figure 9-9.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
  <title>Read Only and Disabled Fields</title>
</head>
<body>
  <p>
<form action="formhandler.php" method="post">
<table cellspacing="10" width="600">
  <tr>
    <td width="25%">
    <p>Customer Code (readonly):</p>
    </td><td>
    <input type="text" size="12" value="X234GG"
      name="code" id="code" readonly="readonly">
    </td>
  </tr>
  <tr>
    <td>
    <p>Discount (disabled):</p>
    </td><td>
    <input type="text" size="10" value=""
      name="discount" id="discount" disabled="disabled">
    </td>
  </tr>
</table>
</form>
</p>
</body>
</html>
Figure 9-9. Figure 9-9

Although the two attributes make the fields look similar on-screen, ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.