Marking fields as required

Jake Howlett, 14 December 2000

Category: Forms; Keywords: fields required

When a form is shown to the user on the web it is a good idea to let them know which fields are compulsory. The de facto way of doing this is to put an asterix (*) after the field label or to use red text for the label. Well, here is a method that not only looks a little better but is dynamic as well.

In the field below, the red circle is used to denote that the field is required.



This is achieved using a background image in the input box. Typically, this is only something that you can do in Internet Explorer. If, like me, you do most of your work on Intranets where the browser version is fixed, this is not a problem.

To do this to a field (called "TestField" in this example) add the following to its HTML Attribute:

@If(TestField=""; "class=\"RequiredField\""; "")


Your form then needs the following Style defined on it somewhere, before the fields, usually in the header:

.RequiredField {
background-image:url(/dbname.nsf/required.gif?OpenImageResource);
background-position:top right;
background-repeat:no-repeat;
}


How can we make this a little more dynamic? How about changing or removing the image once the field has been filled in (validated) ? Look at the form below that has four fields, three of which are required:

Your Detials
Note: A red circle denotes required fields and a green circle is for fields that are OK.

First Name:
Last Name:
Age:
Sex:


Tab through the fields, filling in some values, and see what happens. When you fill in a value in the first field the circle changes colour. In the second field the circle disappears. In the third it remains the same. What you do is up to you really...

How does this work? Well, the onChange event of the first two fields checks to see whether a value has been entered and then changes the Style of the box using its className property. Here is the HTML generated for the first field:

<input type="text" class="RequiredField" name="textfield1" onChange="this.className = (this.value!='') ? 'ValidField' : 'RequiredField'">


You generate this by making the HTML attributes of the field:

@If(TestField=""; "class=\"RequiredField\" "; "") + "onChange=\"this.className (this.value!=\'\') = \'ValidField\' : \'RequiredField\'\"


Note: The Style (class) called "ValidField" is identical to that of "RequiredField" apart from the URL pointing to a graphic called "valid.gif" that is green, not red.

Thanks to Kerry Kilpatrick for pointing out that fields already completed in a document, that is saved and then edited, show as required. Fixed - [23/01/01]