Приглашаем посетить
Культурология (cult-lib.ru)

Developing Forms

Previous Page
Table of Contents
Next Page

Developing Forms

Forms are one of the most interactive elements of any Web site. A Web site might provide information to your visitors, but if visitors are going to provide information in return, that's almost always going to involve a form. My focus here is to show you how you can lay out a form using CSS and a minimal amount of markup, so that you can quickly build form components.

Understanding the Form Element

When I build a form, I first create a container div for the form with the form element inside it, like this

<div id="formcontainer>
  <form method="post" action="../forms_tests/page.htm">
    <!--all form markup in here-->
  </form>
<div>

The container div lets me add related elements for headings and text above and below the form element and set margins around the whole thing.

It's important to understand the purpose of the form element. When the visitor presses the Submit button, the data (name/value pairs) from every input within the form element is sent to the URL defined by the action attribute of the form. The way in which it is passed to that target URL, either by post (not displayed in a destination page URL) or get (visible in the destination page URL), is determined by the method attribute. Each item of a form comprises of the input element (for example, a text field, a menu, etc.) and a text label to let the user know what they should do (for example, Enter your Name, Choose a Car).

My usual approach is to put the label to the left and the input to the right so the user can read what to do and then do it. In the XHTML, I handle each item the same way; I mark up the label with a label element and then follow it with the input element, like this


<div class="clearfix">
     <label>Enter your First Name</label>
     <input onfocus="clearText(this)" name="firstName" type="text" size="35" value ="
Developing Forms enter first name here" />
  </div>

I wrap them both in a div with the clearfix class so that no matter which of the two contained elements is the taller, the next item of the form gets pushed down below them. Then in my CSS, I float the label to the left so the two contained elements sit side by side, and then I add a border to the top of the containing div, so that, as the divs stack up, there is dividing horizontal line between each item.

Figure 7.35 shows how a form might look once you have done the markup of a few items and have made a start on the CSS.

Figure 7.35. Here's a form with some simple styles and borders on the containing divs.

Developing Forms


Here's the CSS that produces Figure 7.35

body {font-family: verdana, sans-serif; color: #003366; font-size:1em;}
* {margin:0; padding:0;}        <-- a
div#formcontainer {width:390px; margin-left:40px; margin-top:20px}
div#formcontainer form  {border:1px solid #CCC;}
div#formcontainer div.clearfix {border-top: 1px solid #CCC;}        <-- b
div#formcontainer form label {width:120px; float:left; font-size:.75em;}        <-- c

(a)Start of the form CSS

(b)Adds the line above each section

(c)This is the text label on the left of each input

Developing Forms

To save space, I have not included the CSS for the clearfix code here, although you do need it for this project. I will include it in code of the final CSS step at the end of this example.


The following is the XHTML for Figure 7.35


<body>
<div id="formcontainer"><!--overall container div-->
 <form method="post" action="../forms_tests/page.htm">
 <!--SINGLE LINE TEXT FIELD-->
  <div class="clearfix">
    <label>Label text goes here and it can be as long as it needs to be.</label>
    <input name="firstName" type="text" size="35" value =" enter first name here" />
  </div>
 <!--MULTI-LINE TEXT FIELD-->
  <div class="clearfix">
  <label>Description</label>
  <textarea name="firstName" rows="6" cols="26">This text area allows multiple lines of
Developing Forms text. Its height can be set and will scroll if user-entered text is not all visible.
</textarea>
</div>
<!--PASSWORD TEXT FIELD-->
<div class="clearfix">
<label>Password</label>
 <input name="firstName" type="password" size="35" value =" enter it here" />
</div>
<!--SUBMIT BUTTON-->
<div class="clearfix">
<input type="submit" value="Submit this Form" />
</div>
</form>
</div><!--end of overall container div-->
</body>

We still have a way to go before we have a good-looking form, but you can see that the two-column effect is visible. In the first item, the label text is longer than the input element, and in the second item, the input is longer than the text, but the items are separated with a horizontal line (the top border of the clearfix div), so your floating and clearing is working properly.

A note on the way the width of the two columns is achievedI set an overall width for the formcontainer div of 390 pixels and set the floated label element to a width of 120 pixels, leaving 270 pixels for the input elements. I don't need to size that explicitly. I arrived at these width values by setting the input text elements to 35 characters wide and then I played with the two width values until it looked right. So, if you want the label text to be wider, simply increase the label's width value by some amount, but don't forget to add the same amount onto the width of the formcontainer as well.

A good next step, now that we can see that the mechanics of the layout are working, is to turn off the border of the form element, add a little vertical space to move the items apart, and find some way to create some space between each label and its related input element (Figure 7.36).

Figure 7.36. A few styles make these first items of your form look good.

Developing Forms


Here's the code

body {font-family: verdana, sans-serif; color: #003366; font-size:1em;}
* {margin:0; padding:0;}        <-- a
div#formcontainer {width:390px; margin-left:40px; margin-top:20px;}
div#formcontainer form  {border-top: 2px solid #CCC; border-bottom: 3px solid #CCC;}      
Developing Forms  <-- b
div#formcontainer div.clearfix {border-top: 1px solid #CCC; padding:10px 0px;
Developing Forms vertical-align:top;}        <-- c
div#formcontainer form label {width:120px; float:left;font-size:.75em; color: #003366;  
Developing Forms margin:0 10px;}        <-- d

(a)Start of the form CSS

(b)The top border is visually 1 px thicker because it touches the div.clearfix bordertop

(c)Adds the line above each section and provides vertical spacing

(d)This is the text label on the left of each input

As planned, I've removed the border from the form element, added the padding on the clearfix div to give some vertical spacing between the form elements and the dividing lines, and added the 10-pixel left and right margins on the label element. This added margin space creates some horizontal space on each side of the label, indenting it from the edge of the lines on the left, and making some space between it and its input element on the right.

Now it's time to move on to some more complex parts of the form where you need to have a number of select elements on the right side, not just a simple text field.

Adding Radio Buttons and Check Boxes

Other types of elements in a form include radio buttons and check boxes. Let's add some markup for a set of three radio buttons and three check boxes, like this


<!--RADIO BUTTONS-->
   <div class="clearfix">
      <label>Pick One</label>
      <div  class="buttongroup clearfix"><!--box for buttons group-->
      <div class="clearfix">
<input  name="radioset" type="radio" size="35" value =" Choice_1" checked="checked" 
Developing Forms/><label>Choice 1</label></div>
      <div class="clearfix"><input  name="radioset" type="radio" size="35" value ="
Developing Forms Choice_2" /><label>Choice 2</label></div>
      <div class="clearfix"><input  name="radioset" type="radio" size="35" value ="
Developing Forms Choice_3" /><label>Choice 3</label></div>
      </div><!--end of box for buttons group-->
    </div> <!--END RADIO BUTTONS-->

       <!--CHECK BOXES-->
    <div class="clearfix">
      <label>Pick One</label>
      <div class="buttongroup clearfix"><!--box for buttons group-->
      <div class="clearfix"><input  name="boxset" type="checkbox" size="35" value ="
Developing Forms Choice_1" />Choice 1</div>
      <div class="clearfix"><input  name="boxset" type="checkbox" size="35" value ="
Developing Forms Choice_2" />Choice</div>
      <div class="clearfix"><input  name="boxset" type="checkbox" size="35" value ="
Developing Forms Choice_3" checked="checked" />Choice 3</div>
   </div><!--end of box for buttons group-->
    </div> <!--END CHECK BOXES-->

This markup is similar to that of the text fields except that instead of a single text field that appears on the right side of our layout, we have a containing div for the group of buttons, and inside of it, we have three divs that each contain a button input element (radio or check box) and some text. If this sounds a little complex, check out Figure 7.37 where, temporarily, the containing div for the group has a thick border and each inner div has a thin border; this figure might make things clearer.

Figure 7.37. Borders around the radio boxes and check boxes and their containing elements illustrate how the elements are organized.

Developing Forms


Before I show you the CSS you need to achieve this layout, I want to share two quick observations on the markup.

First, the way that you get a group of radio buttons or a group of check boxes to behave as a group is to give them all the same name attribute. Then, for example, if you click one of the radio buttons, any other that is selected is deselected. Although each button in a group shares the same name, each button must be given a unique value so that the name/value pair (passed to the URL defined in the action attribute of the form when the form is submitted) conveys which selection (value) from the group (name) was made. Note that in the preceding markup, all the radio buttons have a common name, as do the check boxes.

Second, you can have one radio button in a group or any number of check boxes preselected when the page loads. You make this happen by adding the selected attribute and setting its value to selected. Note in the preceding markup that the first radio button and the last check box are preselected in this way.

Here's the CSS that organizes the elements in the group one above the other in the containing buttongroup div, as illustrated in Figure 7.37.

div#formcontainer div.buttongroup {float:left; border:0; padding:0px;}        <-- a
div#formcontainer div.buttongroup div {margin-bottom:5px; font-size:.75em;}        <-- b
div#formcontainer div.buttongroup input {margin-right:5px;}        <-- c

(a)A container for a groups of buttons; suppresses the clearfix div top border on the divs around the radio buttons/check boxes

(b)Wrapper for the INPUT and its text; margin-bottom sets the vertical distance between buttons

(c)Set the distance between button and its label text

Again, the key to the success of this rather simple CSS is the float on the containing div and its clearfix class that wraps it around the elements within. The rest of the markup is just spacing to improve the overall layout.

Developing Forms

Right after the float:left in the markup above is border:0. This is here because the big container div that surrounds each section of the form has a border-top line to create the horizontal separators, and we use the same clearfix class on these inner containers. So we have to set the border-top of this new inner container to zero explicitly, otherwise we would have an unwanted line, defined div.clearfix, along the top of each containing div for our button groups also. Try removing that border:0 to see what I mean.


The last form element I'll illustrate in this form example is a pop-up menu, known as a select.

Creating a Form Select

Menus generated using the select tag are often used in forms for selecting State and Country names in the checkout area of e-commerce stores and in other situations where the user must choose one item from a large number of options. Unlike check boxes and radio buttons, a select is very compact because it only occupies the space of single line until the user clicks it.

The markup for a select is structured in a similar way to a list; it contains a select element with a number of option elements within it, like this

<!--DROP DOWN MENU-->
     <div class="clearfix">
   <label>Pick from menu and then click submit below</label>
    <select name="menuChoice">
   <option value="no_selection_made">Pick your favorite guitar</option>
   <option value="fender">Gibson</option>
   <option value="fender">Fender</option>
   <option value="taylor">Taylor</option>
   </select>
   </div>
   </div>

Figure 7.38 shows you what you get.

Figure 7.38. A select element creates a menu within your form.

Developing Forms


This element doesn't require any extra CSS; you can just add the markup. The same CSS that is used on the text fields works here too.

XHTML allows you to add submenus to select elements using the optgroup tag, but this is so poorly supported in the various browsers that it hardly seems worth demonstrating here.

TWO FINAL TOUCHES

The first final touch is to move the Submit button to the right; it just seems that users expect it to be there. Also, if you must add a Reset button for the form, put it to the left because this is visually perceived as being out of the way and is not as likely to be clicked accidentally. The simple way to do this is to add a special class to it and either float it to the right or add a lot of margin-left. The elegant way, on the other hand, is to select it using an attribute selector that requires no additional markup but simply allows you to write a selector that selects only an input with the submit attribute. It's elegant, but IDWIMIE. So in Internet Explorer, you get the button on the left; it's not a disaster.

Developing Forms

To see the final CSS along with the complete markup, go to the Stylin' Web site (www.bbd.com/stylin).


The second final touch is to add a small JavaScript function into the head of the document that clears default text out of the fields when the user clicks in them. This allows a field to contain instructions, as stated in the value attribute of the input, for the user (such as: Enter 16 digit card number without spaces), which obligingly disappear when the user clicks in the field. As you can see, I have added the clearText JavaScript function in the head of the document and, on each select, where I want to use text prompts for the user, I have added the onfocus attribute to call that function and clear the text when the user click in (moves the keyboard focus) that text field.

After you make these changes, your final form looks like Figure 7.39.

Figure 7.39. Here's the completed form.

Developing Forms


A form like this can run to many lines of code, and when you have an e-commerce site form for credit card information that includes a select with 50 state names in it and another select with 300 country names, well, let's just say it doesn't get any shorter. However, as in this case, forms are usually the same elements with slight variations over and over, so although they can run into many lines, they are not too complicated to develop, review, and modify.

    Previous Page
    Table of Contents
    Next Page