Web Development · Lesson 6

Web Forms

How forms, Web servers, and scripts exchange data, and how to build and test every common HTML5 form field.

  • web-forms
  • html-forms
  • input-types
  • cgi
  • form-validation

Lesson purpose

Lesson 6 moves students from pages that only display information to pages that collect it. Students learn how a Web form, a Web server, and a server-side script work together; how the browser packages form input as name=value pairs; and how to build every common field type with <form>, <input>, <select>, and <textarea>. Through a chain of short labs they grow one form field by field and watch a test engine echo back what each field submits. The lesson closes with design judgment: CAPTCHAs, search engine optimization, and choosing the right field for each kind of answer.

Big idea for the day: a form is only half of the system. The HTML builds the fields; a script on the server does something with the data. Without that script, a form does nothing useful.

Learning objectives

By the end of the lesson, students should be able to:

  • CIW 2.4.1: Construct and test HTML forms.
  • CIW 2.4.2: Identify ways that CGI scripts can parse and transmit information from a form, including email, FTP, HTTP, and HTTPS.
  • CIW 2.18.4: Activate features provided by managed services (e.g., CGI, forms).
  • Explain the roles of the browser, form, Web server, and server-side script.
  • Read and predict a raw name=value string.
  • Choose the correct field type and attributes for a given piece of information.

1. What a Web form does

Websites use forms to obtain input from users: names, addresses, email addresses, payment details, survey answers, and more. A single form can contain several field types.

  • The user fills in the fields and clicks Submit. The browser uploads (or emails) the data to the receiving server, where it is stored and/or processed.
  • Many forms also provide a Reset button, which clears entered data and returns every field to its default value instead of submitting.
  • Forms are part of standard HTTP, which can carry almost any type of data to a Web server.

The Web Forms video gives a one-pass overview of the whole lesson: why forms exist (think of any online purchase), CGI as the long-standing standard for extending a Web server, how submitted data travels as name=value pairs, the <form> container and its field tags, the common field types, and CAPTCHAs. It works well as the opener.

2. Forms, Web servers, and server-side scripts

To be truly functional, a form needs:

  • A Web server technology such as IIS, Tomcat, or Apache Web Server.
  • A server-side scripting processor such as PHP, ASP.NET, or Java to interpret the input.

Contrast the two kinds of scripts:

  • Server-side script — code that lives on the server and processes form input there.
  • Client-side script — code embedded in the page, downloaded to the user’s computer, and run in the browser (for example, JavaScript). JavaScript can also send form data.

A Web server performs several jobs for a form:

  1. Receives data from a Web form or client-side script.
  2. Processes and reformats the input.
  3. Stores data in databases or file systems.
  4. Resends data to other servers for further processing or storage.
  5. Responds to client requests.

Web servers and server-side languages run on Linux/UNIX, Mac, and Windows. Most are free to use, but sustained technical support usually requires a paid service agreement, and some products need a commercial license — read the user agreement.

CGI

The Common Gateway Interface (CGI) predates modern Web servers but is still used in hardware-embedded software and legacy applications. A CGI program lets a Web server pass control to a software application: it receives client input, processes it, performs server-side actions (storage, communication with other servers), and responds. Server-side CGI scripts have traditionally been written in Perl; alternatives include PHP, JSP, ASP.NET, and ColdFusion.

Instructor note from the book: students do not need deep CGI detail. They must understand that a form is useless without a CGI script or an alternative to process it.

Visualizing client-server communication

Four pieces are required:

  1. Web browser — displays the form and sends the data.
  2. Web form — the fields the user fills in.
  3. Web server — receives the request.
  4. Server-side script or CGI script — processes the data. The processing script stays on the server.

What the server-side script can do with the data:

  • Store it in a database (for example, a bank account update).
  • Search a database (for example, a book or movie on Amazon.com).
  • Send processed information back to the user (a new balance, a shipping confirmation).

Figure 6-1 traces one round trip: the browser submits, the server hands the data to the script, the script acts, and a response returns to the browser.

3. Parsing data: name=value pairs

When the user clicks Submit, the browser sends the form’s contents to the server as a raw text string made of name=value pairs. The name attribute on each field supplies the “name” half.

Enter Your Name: <input type="text" name="Name" size="40">

Enter Your Email: <input type="text" name="Email" size="40">

Should we add you to our mailing list? <br>
<input type="radio" name="AddToList" value="yes"> Yes
<input type="radio" name="AddToList" value="no"> No

If Dimitri Pappas fills this in, the server receives:

Name=Dimitri+Pappas&Email=student50@class.com&AddToList=yes

Point out each rule:

  • Each field becomes name=value; you choose the name words.
  • & separates the pairs.
  • + replaces spaces the user typed.
  • An empty field returns only its name and an equal sign, such as Email=.

A CGI script then parses the string into a human-readable format:

Name:          Dimitri Pappas
Email:         student50@class.com
Mailing List:  Yes

Clarification to share: the book’s example of an empty field says the mailing-list option would return Email=, which mixes up two fields. An empty text box returns its own name with nothing after = (for example, Email=). A radio group or checkbox with nothing selected is usually not sent at all.

Check for understanding: “What string would the server receive if the user typed Ann Lee and chose No?” (Name=Ann+Lee&Email=...&AddToList=no.)

Ways a script can transmit form data

Objective 2.4.2 expects students to recognize that a script can send or deliver form data by email, FTP, HTTP, or HTTPS. Any form collecting personal information should be submitted over HTTPS so the data is encrypted in transit.

4. HTML5 and forms

HTML is a markup language, not a programming language: tags tell the browser how to display content. The basic form elements in HTML5 are little changed from HTML 4.01. The main differences:

  • CSS3 handles all form styling.
  • HTML5 adds new form elements and attributes and new <input> types that give better control over validation and input.

The book points to the W3Schools HTML Forms reference for the full list of HTML5 form features.

PHP mail()

PHP’s mail() function is a common way for a server-side script to email form results. It can send plain text, HTML, or an attachment.

bool mail ( string $to , string $subject , string $message , string $headers , string $parameters )
  • $to — the receiver(s).
  • $subject — the subject line.
  • $message — the message body.
  • $headers (optional) — extra headers such as From, CC, and BCC.
  • $parameters (optional) — extra parameters for the sendmail program.

This is awareness, not a coding requirement: students read PHP here, they do not write it.

5. The <form> element

The <form> tag is a container that wraps every field in the form. Always include the closing </form>:

  • Older browsers may not render or submit a form that is missing </form>.
  • HTML5 is forgiving and will usually still submit, but results are unpredictable. With two forms on a page and the first left unclosed, the second form’s data is submitted with the first. JavaScript that processes the form may also fail if the form’s end is unclear.
  • Closing forms properly makes your intent clear to other developers.
<form method="post"
      action="http://www.anyserver.com/cgi-bin/scriptfile">
  <input ...>
  <select> ... </select>
</form>

Attributes of <form>:

Attribute What it does Default
method How the browser sends data to the server get
action Name and location of the script that processes the form —
enctype How submitted data is encoded URL-encoded
autocomplete Whether the browser may autocomplete fields on
accept-charset Character set used for submitted data the page’s charset
name Identifies the form —
novalidate Tells the browser not to validate the form —
target Where to display the response from action _self

method and action are the two attributes a form needs to process data.

method: get vs. post

  • get — appends the form data to the URL as a query string. It is visible in the address bar, history, and logs, and it sends data in cleartext, so it is less secure and limited in length.
  • post — sends the data to the action URL in the body of the request. It can send more characters and is the preferred method for form data, although it can require a bit more processing by the script.

Precision note: the book calls post “secure.” It is more private than get because the data is not in the URL, but it is not encrypted. Only HTTPS encrypts form data in transit. Use post over HTTPS for anything sensitive.

action

action names the CGI or other server-side script (for example, PHP) that will process the form. Instructor note: most hosting providers offer ready-made form scripts; students who run their own servers must write and maintain their own. Reading a form’s action value tells you what processes it — the class test engine, for instance, is a script at a cgi-bin address.

The The <form> Tag video recaps the form attributes, get vs. post, action, and the three field tags that follow; use it before Exercise 6-1.

6. The field tags: <input>, <select>, <textarea>

All field tags go between <form> and </form>.

  • <input> — an empty (stand-alone) element. Its type attribute decides what it becomes: text box, password field, radio button, checkbox, Submit or Reset button, and the newer HTML5 types.
<input type="radio" name="AddToList">
Enter Your Password: <input type="password" name="Password" size="14">
  • <select> — a container holding <option> elements; it creates single- or multiple-option lists.
  • <textarea> — a container that creates a scrolling, multi-line text box. Text between its tags appears as default text.

Instructor note: <select> works like the list tags students already know — one container holding repeated item tags.

7. Form field types at a glance

Students must recognize every field in Table 6-1:

Field What it is How to create it
Text box Single-line text entry <input type="text">
Radio button Round buttons; one choice from a group <input type="radio">
Checkbox Square boxes; any number of choices <input type="checkbox">
Single-option select list Drop-down list; choose one <select>
Multiple-option select list Exposed, scrollable list; choose several <select multiple>
Text area Multi-line scrolling text box <textarea>
Password field Text box that masks characters <input type="password">
Email field Text box that requires an @ address <input type="email">
File upload Button and field for choosing a local file <input type="file">
Submit button Sends the form to the action script <input type="submit">
Reset button Clears fields back to defaults <input type="reset">
Number field Numeric input with optional limits <input type="number">
Date / time field Date or time entry, often with a picker <input type="date">, type="time"
Range Slider for an approximate number (0–100 by default) <input type="range">

Not every form needs many fields. Figure 6-4 shows a small login form embedded in other page content — short forms are common and often better.

The name attribute

Every field shares the name attribute. It labels the data in the results so you know what each value means. Example: checkboxes for gardening, sailing, and biking all named Interests return Interests=sailing when the user checks sailing.

8. Text boxes and password fields

The text box is the most common field and collects one line of data.

<input type="text" name="FieldName">
<input type="text" name="FieldName" value="DefaultText">
<input type="text" name="FieldName" placeholder="Expected value of input">
  • value — real default text that is submitted if the user leaves it.
  • placeholder — a light-gray hint that disappears when the user starts typing; it is not submitted. It works with the text, email, and password types.
  • size — the display width in characters; it does not limit how much can be typed.
  • maxlength — the maximum number of characters allowed; it does not change the width.

Common confusion: size vs. maxlength. One controls appearance, the other controls input.

Modern practice (preview): give each field a visible label tied to it with <label for="..."> and a matching id. Screen readers announce the label, and clicking the label focuses the field. Placeholder text is not a substitute for a label.

<label for="email">Email</label>
<input type="email" id="email" name="Email">

9. File upload

Provide your resume here: <input type="file" name="UploadedFile">

This creates a Browse / Choose File button and a box showing the chosen file’s path. In practice the form must use method="post" and enctype="multipart/form-data" for the file itself to be sent.

10. Submit and Reset buttons

  • type="submit" sends all field data to the script named in action. Its default label is “Submit” or “Submit Query.”
  • type="reset" clears all fields and restores their defaults. Its default label is “Reset.”
  • Either label can be changed with the value attribute.

Tech note: the labs point action at a public test engine that echoes your submitted name=value pairs back to the browser. It exists only to verify that a form works; never use a test URL in production.

Instructor note: students can read the action value to see that the class test engine is a script on a CGI path, which returns each field’s name and value.

11. Radio buttons

Radio buttons offer two or more mutually exclusive options — never a single stand-alone button.

Should we add you to our mailing list? <br>
<input type="radio" name="AddToList" value="yes" checked="checked"> Yes
<input type="radio" name="AddToList" value="no"> No
  • Every button in a group shares the same name; that is what makes them exclusive.
  • Each button has its own value, which is what the server receives.
  • checked="checked" preselects a default (in HTML5, checked alone also works).

Design discussion from the lab: a default saves users time, but some users never change it even when it is not their preference. How might an organization use (or misuse) that?

Troubleshooting: if both buttons can be selected at once, their name values do not match.

12. Checkboxes

Checkboxes offer non-exclusive choices; users may check any number, and you may preselect as many as you like with checked. The keyword is checkbox — one word, no space (a common student error).

Two ways to name a group, chosen by how the data will be used:

<!-- Separate fields: each choice is its own name -->
<input type="checkbox" name="ad"> Online Advertisement<br>
<input type="checkbox" name="friend"> From a Friend<br>
<input type="checkbox" name="convention"> Trade Convention<br>

<!-- One grouped field: every choice shares a name -->
<input type="checkbox" name="Origin"> Online Advertisement<br>
<input type="checkbox" name="Origin"> From a Friend<br>
<input type="checkbox" name="Origin"> Trade Convention<br>
  • Separate names store each choice in its own database field — useful when you need to know exactly which options were chosen.
  • A shared name treats the choices as one field — useful when you only need to know that the person chose at least one.

Modern practice: add a value to each checkbox (for example, value="friend"). Without one, a checked box submits the word on, so a shared-name group cannot tell you which boxes were checked.

13. Select lists

Single-option (drop-down) list

<select name="listName">
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option n</option>
</select>
  • By default the submitted value is the option’s visible text.
  • Add value="..." to an <option> to submit something different from what the user sees.

In Lab 6-5, the Never option uses value="Remove", so the script receives EmailFreq=Remove. A script could use that to drop the person from a mailing list automatically while keeping the address on file.

Multiple-option list

<select name="work" multiple="multiple" size="4">
  • multiple lets users choose more than one option (Ctrl+click on Windows, Cmd+click on Mac).
  • size sets how many options are visible in the scrolling box. Without it, the number shown depends on the browser (older Internet Explorer showed four).
  • Multiple-option lists are usually shown open, with several options exposed.

14. Scrolling text area

<textarea> collects several lines of text — comments, an address, a letter. It can contain only text, and any text between the tags appears as default content.

Attribute What it does Values
cols Width in characters integer, e.g., 30
rows Number of visible lines integer, e.g., 3
wrap Whether submitted text includes line breaks soft (default, no breaks added) or hard (adds newlines; requires cols)

wrap was deprecated in HTML 4.01 and revived in HTML5 with the soft and hard values (replacing the older none and virtual). It matters only to scripts that process the text.

15. HTML5 input types: number, date/time, range

Number

<input type="number" name="quantity" min="1" max="10">
Attribute Purpose
max Largest allowed value
min Smallest allowed value
step Legal intervals between values
value Default value

The browser adds up/down arrows and rejects values outside the limits when the form is validated.

Date and time

<input type="date" name="date">
<input type="time" name="time">
<input type="datetime-local" name="datetime">

Depending on browser support, a date or time picker appears. datetime-local collects both at once.

Range

<input type="range" name="feedback" min="1" max="10">

A slider for a number whose exact value is not important. The default range is 0–100; min, max, step, and value customize it.

16. Web forms and CAPTCHAs

A CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) is a challenge-response test that separates people from automated “bots,” mainly to stop spam form submissions and fake account sign-ups.

  • Text CAPTCHAs show distorted text that people can read but machines struggle to; the user types the text before the form is accepted.
  • Image CAPTCHAs ask the user to pick the parts of an image containing a specific object.
  • Audio CAPTCHAs read characters aloud so users who are blind or have low vision can pass the check — an accessibility requirement.
  • As AI improved, bots learned to solve these challenges, so the approach evolved into Google’s reCAPTCHA: first distorted words, then a single “I’m not a robot” checkbox that analyzes the user’s behavior instead of a puzzle, and later a version that scores behavior in the background.

Accuracy note: the book’s version names and years for reCAPTCHA are somewhat muddled. The key idea for students is the trend — from puzzles people must solve to behavior analysis that stays out of the way. Future approaches may use technologies such as facial recognition.

17. SEO and Web forms

Search engine optimization (SEO) means learning how search engines such as Google or Bing rank sites and designing pages — including forms — to rank as high as possible. Form-related strategies from the book:

  • Keep forms as simple as possible; each extra field may reduce the score.
  • A CAPTCHA or other human-only step may lower a page’s score because bots stop there.
  • Give fields informative, descriptive labels.
  • Provide proper alt text for images.
  • Provide a clear call to action; do not rely on a generic Submit button.
  • Provide alternative text navigation.
  • Build responsive sites.
  • Cross-link pages so important pages receive more links.

Classroom application

Lab 6-1: Studying the PHP mail() function

Students copy mailer.zip from Lesson06\Lab_6-1 to the Desktop, extract mailer.php, open it in a text editor, and identify each part of the mail() call. They note the two settings needed for basic operation — $subject and $message — and can consult the PHP manual for details. Discussion: How could you use this function in your own situation?

Labs 6-2 through 6-10: Building one form field by field

Each lab opens the previous file and saves it under the next lab’s name (lab_6-2.html → lab_6-3.html → … → lab_6-10.html). The action points at the CIW public test engine, which echoes the name=value pairs back. When the browser warns that the information you’re about to submit is not secure (the test engine uses plain HTTP), students choose Send anyway — a good moment to reinforce why real forms use HTTPS.

After every lab: load, test, submit, use Back, and validate at the W3C Markup Validation Service.

Lab 6-2 — Simple form. Starting from lab_6-2.txt, students build the page shell and a form with Name and Email text boxes plus Submit and Reset, save it as lab_6-2.html, submit it, and see the test engine return the pairs.

<form method="post" action="http://ss1.ciwcertified.com/cgi-bin/process.php">
  Enter Your Name: <input type="text" name="Name" size="40">
  <br><br>
  Enter Your Email: <input type="text" name="Email" size="40">
  <br><br><br>
  <input type="submit">
  <input type="reset">
</form>

Lab 6-3 — Radio group. Add the Should we add you to our mailing list? Yes/No group (name="AddToList", Yes preselected). Test that only one can be selected, then confirm the result shows yes or no.

Lab 6-4 — Checkboxes. Add How did you hear about uCorp? with three checkboxes named ad, friend, and convention. Submit with two checked and note each appears as its own field (Figure 6-12). Then rename all three referred, resubmit, and compare: the results now show one grouped field (Figure 6-13). Discuss when each approach fits, then restore the separate names (the book capitalizes them Ad, Friend, Convention at this step, and the next lab’s code shows name="Convention"; either works as long as students are consistent).

Lab 6-5 — Single-option list. Add How often would you like to receive an email from uCorp? with name="EmailFreq" and four options, the last being <option value="Remove">Never</option>. Submit once with the second option, then with Never, and see Remove returned.

Lab 6-6 — Multiple-option list. Add When is the best time of day to reach you? with name="timeofday" multiple="multiple" size="3" and four options (Morning through Evening). Ctrl+click to choose several and confirm all are returned.

Lab 6-7 — Text area. Add Comments: with <textarea name="comments" cols="30" rows="3"></textarea>. Instructor note: have students view the form in two browsers and compare. If time permits, add default text between the tags.

Lab 6-8 — Number field. Add Your age: with <input type="number" name="age" min="15" max="65"> above the comments.

Lab 6-9 — Date field. Add We are serving you since: with <input type="date" name="date">.

Lab 6-10 — Range. Add Do you like us? with <input type="range" name="rating" min="1" max="10" value="5"> and confirm a number from 1 to 10 is returned.

Upgrade to discuss: the labs collect email with type="text". Changing it to type="email" lets the browser check for a valid address and shows an email keyboard on phones.

Optional Lab 6-1: Information Request form for uCorp

The Web development director asks for a live Contact Us form that collects first and last name, email address, skills, and any additional information, using the site’s look and feel. Students copy contactus.txt and the contactus/ folder from Lesson06\Optional_Lab_6-1 into uCorp/, save the shell as contactus.html (the book’s step mistakenly says form.txt), and replace <!-- PLACE YOUR FORM HERE --> with fields matching Figure OL6-1.1: First Name, Last Name, Company, Phone Number, Email Address, Country, a Comments text area, a multiple-option list of days to be contacted, checkboxes for Morning/Afternoon/Evening, a Yes/No mailing-list radio group, and Submit. They adjust the CSS, test in at least two browsers, and validate. A finished version is in the lab files’ Finished folder.

In-book exercises and activity

  • Exercise 6-1: The <form> tag — matches method, action, get, and post to their descriptions.
  • Activity 6-1: Identifying HTML form elements and attributes — matches action, <form>, <input>, value, <select>, name, cols, <textarea>, and method to their roles. Use it after the text area section.
  • Exercise 6-2: Web Form Fields — two sets: matching form elements and attributes, and choosing the field type (text box, radio buttons, checkboxes, single- or multiple-option list) that fits each description.

Case study: In Good Form

Lola builds a form for her college’s Language Department to plan a summer trip to Europe. It collects gender (radio buttons), languages studied (checkboxes), preferred countries (scrolling text area), hotel room preferences (drop-down list), and limitations related to physical abilities, diet, allergies, religious practices, and so on (text box).

Discussion prompts and target answers:

  • Did Lola choose the right fields? Mostly. Preferred countries would be better as checkboxes or a select list; free text invites spelling errors and forgotten options and is hard to tally.
  • What other fields could work? A scrolling text area for limitations, since those answers can be long. Many fields have reasonable alternatives — let students defend their choices.
  • What else might faculty ask for, and with what field? Available travel dates — for example, checkboxes for date ranges, or HTML5 date fields.

Privacy point to raise: several of Lola’s fields collect sensitive personal information (health, diet, religion). Collect only what is needed, submit over HTTPS, and tell students how the information will be used.

Application project

Visit several sites that use forms and view their source. Can students find the <form> element and tell from method and action where the form is processed? Traditionally that meant a Perl CGI script; today it is more often PHP, JSP, or another server-side technology.

Common misconceptions

  • “The HTML form saves the data.” HTML only collects it; a server-side script processes and stores it.
  • “post is encrypted.” It keeps data out of the URL but is not encrypted; HTTPS provides encryption.
  • “size limits how much a user can type.” size sets width; maxlength limits characters.
  • “Placeholder text is the same as a default value.” A placeholder is a hint that is not submitted; value is real default data.
  • “Radio buttons in a group need different names.” They must share one name and use different values.
  • “check box works as a type.” The keyword is checkbox, one word.
  • “A select list always submits what the user sees.” An <option value="..."> submits the value instead.
  • “Leaving off </form> is fine in HTML5.” It may render, but it can merge forms and break scripts.
  • “CAPTCHAs have no downside.” They can hurt accessibility and SEO; audio alternatives and newer behavior-based checks exist for that reason.

Key terms

  • Client-side script — code embedded in a page and run in the user’s browser; JavaScript is the common example.
  • Server-side script — code on the server that processes form input; CGI scripts have traditionally been written in Perl.
  • Common Gateway Interface (CGI) — a standard that lets a Web server pass user-submitted data to a program, which organizes it and returns a consistent result.
  • name=value pair — the basic unit of submitted form data, joined by &, with spaces sent as +.
  • CAPTCHA — a challenge used to tell human users from automated bots before accepting a form.
  • SEO — designing pages so search engines rank them as highly as possible.

Lesson summary

  • A working form needs a browser, the form, a Web server, and a server-side script such as CGI, PHP, or ASP.NET.
  • Submitted data travels as name=value pairs separated by &, with spaces as +; the script parses them into readable results and can send them by email, FTP, HTTP, or HTTPS.
  • <form> wraps every field; method (get or post) and action (the processing script) are what make it work. Always close the form.
  • <input> with a type creates text, password, email, file, radio, checkbox, submit, reset, number, date, time, and range fields; <select> creates single- or multiple-option lists; <textarea> creates multi-line text boxes.
  • name labels every field’s data; radio groups share a name; checkbox naming depends on how the data will be used; value controls what is sent.
  • Test forms by submitting to a test engine and validating the code; use HTTPS and collect only what you need in real forms.
  • CAPTCHAs block spam but affect accessibility and SEO; keep forms short, clearly labeled, and easy to act on.

Next lesson: Video, Audio and Image Techniques — adding video, audio, image maps, and optimized images to pages.