Reading: Chapter 14 of your book Head First HTML and CSS discusses HTML Forms. At this lecture, we will not discuss how forms talk to the server, but will only focus on the HTML elements that go into a form, see pages 652-659 (What can go in a form) and 662-672.

This reading is entirely about HTML, but forms are the primary way of getting input from the user, and we will then turn to how that input can be accessed using the DOM and jQuery and then processed by our JavaScript code. To add the form processing functionality, we'll have to learn about events and event handlers, which is in the next reading. This reading is just HTML.

We will not be covering all aspects of HTML forms. We'll focus on just a handful that are useful in this course. If you want to learn more, there's some additional material at the end, and you're welcome to talk to one of us. The most important kinds of inputs we'll learn are:

The form tag

HTML has a dedicated tag, form that is used as a container to package data that might be sent to a web server. The attribute method of the element allows the form to either request data from the server (method="GET"), or send data to the server (method="POST"). However, in order for both these operations to happen, the server needs to have some dedicated programs (also known as scripts) that can deal with the form data. At this point, we will not talk about how this happens (we'll postpone this discussion for later in the semester), and only concentrate on the HTML elements that are contained inside the form.

Let's see an example form, and then we'll look at the code that creates it.

A note on styling

If you see the above form outside an HTML page with CSS, it will look different. Our lecture page applies styling to it that is not the default way a browser will display a form. Please see how the unstyled form looks like.

Additionally, keep in mind that all form elements are inline elements, therefore, in order to appear in separate lines, we wrap them in p elements.

Here's the code that creates that form:

  

As you can see, there's an outer FORM element that wraps up the form inputs. There are input elements that correspond to different places where the user can enter information. Most of the inputs use the INPUT tag, but some use tags like SELECT (for a drop-down menu) and TEXTAREA (for larger blocks of text). The general term is control. Finally, there's a BUTTON input at the end. In a more complete example; clicking this button would send the form data to the web server; this one doesn't do anything.

Form Fields

Let's look at the different input elements. The following table shows the HTML syntax for including different HTML elements in a form. As you will notice, the most common element is <input>, which, based on the value for its attribute type will display a different kind of input. Play with the rendered version of a tag in every row in the table.

Tag Name Rendered Tag More Info
<input type="text">
Your Age: <input type="number" min="1" max="120">
Your Age:
<input type="range" min="100" max="200">
<input type="date">
<input type="time">
<button type="button">Click me</button>
<textarea rows="2" cols="10"> You can type here</textarea>
<select><option>Black <option>White </select>

For more information on the form elements and all its fields, consult the W3Schools page on forms.

Let's look at some of the more important controls, and then other aspect of

The INPUT Tag

The input tag is fairly straightforward, but you can specify the type of input you are looking for, using the TYPE attribute. It has many more types, which we are not listing here; consult W3Schools page for input to see the complete list. Here are just a few:

Some of these types (such as time, date, number, range, etc.) were introduced in HTML5, which means that not all browser versions are able to support them. For maximum portability, you should stick to type=text. However, sliders like we get with type=range are fun, and we'll use them in this course.

The SELECT input

To specify a menu, from which the user can choose only one option, you use the SELECT tag inside the form. You specify the NAME of the input in the SELECT tag, and each menu item is specified using the OPTION tag. Here's an example:

<form action="">
  <p>Drink:  <select name="beverage">
      <option value="">choose one
      <option value="Coke">Coca-Cola</option>
      <option value="Pepsi">Pepsi-Cola</option>
      <option>Beer</option>
      <option>Wine</option>
   </select>
</form>

(The closing </option> tag is optional, like a closing </p> tag or </li> tag, but it's best to use it.) Any option can have a separate "value" attribute; if none is specified, the value is the option itself.

Specifying a non-option as the first item in the list helps to tell whether someone has actually made a choice or just overlooked this menu. Making the non-option have a value of the empty string helps with validating the form.

The TEXTAREA input

If you want to allow your user to type in a long response, you should define a textarea inside your form. This tag has attributes called ROWS and COLS that let you specify the size of the area.

<textarea name="thoughts" rows="3" cols="40">
A chicken is an egg's way of making another egg
</textarea>

The default value is the region between the beginning and ending tag. Typically, you want the default value to be empty, so put the tags right next to each other, as in this example here:

<textarea name="thoughts" rows="3" cols="40"></textarea>

Don't let even a single space creep in, or the initial value will be a string of one space, and not the empty string. That will affect any code that cares about the default or original value, such as certain kinds of validation

Labels

A form consisting of a bunch of bare boxes would be useless, so how is the user to know what input box means what? That's done with the label tag. There are two ways the label can be used. One option is to wrap the input in the label:

<label>
  Given Name
  <input type="text" name="givenname">
</label>
<label>
  Family Name
  <input type="text" name="familyname">
</label>

The other is to give the input an ID and reference that ID in a for attribute of the label:

<label for="givenname">Given Name</label>
<input type="text" name="givenname" id="givenname">
<label for="familyname">Family Name</label>
<input type="text" name="familyname" id="familyname">

The latter is a bit more work, but is necessary in some cases where the structure of the HTML doesn't allow the input to be a child of the label, as with a table.

Name and Value

When the form gets submitted, the form data gets sent to the server. It gets sent as a set of name/value pairs, which we can think of as like a little table. Here's some data as if from our pizza form:

namevalue
customerHermione
phone555-8888
addrhgranger@hogwarts.ac.uk
sizelarge
due21:00
instructionsplease deliver by owl

Since the fields of a form need to be processed both by Javascript code on the client-side (by the browser) and the scripts on the web server, it is necessary to use the different attributes of these elements to distinguish and access them.

Consequently, the two most important attributes that we will use very frequently are name and value.

Size of Text Inputs

To control the width of the text input field, you don't use the attribute width, but the attribute size. For example, <input value="Wellesley" size="10"> will now be much smaller than in the example above: .

Placeholder

Another useful attribute for input controls is placeholder, which can be used to provide a hint for the kind of value that should go in a field. For example, this HTML <input type="text" placeholder="Enter your name"> will be rendered like this: .

Form Validation

Later in the course, we'll talk about submitting the form data to a server for more elaborate processing, but before we do that, we should discuss validation. What is form validation? Essentially, it means checking to see that the form has been filled out correctly (as far as we can tell).

Form validation could be used to ensure that someone hasn't overlooked a text input, menu or radio button group, and can check that, for example, the zip code is 5 digits (or 9) and that a telephone number is 10 digits, and that an email address looks like an email address.

Form validation can actually cancel the submission of the form, so that the data never leaves browser. The reason we validate forms is twofold: to give the user immediate feedback that they've missed something, instead of waiting for the server to respond, and to protect the server from having to handle all those invalid forms. Of course, a determined nefarious person can simply disable our form validation JavaScript and hammer our server with invalid forms, but that's rare. The vast majority of invalid forms are just human error.

Obviously, the browser can't tell whether you entered your correct phone number, but it can check that you typed the right number of digits (and only digits). Similarly, it can't check that your spelled your name correctly (and whether your name really is Mickey Mouse), but it can check that you didn't leave that input blank.

With HTML5 and modern web browsers, form validation has gotten a lot easier. In the past, web developers would write JavaScript code that would look at the values in the form to check for bogus values. They wrote libraries and jQuery plug-ins to make the job easier for others. Indeed, there is a jQuery plug-in by Jörn Zaefferer called validation that does a good job and is well described in our book, JavaScript & jQuery: The Missing Manual, pages 278-300. Please read that, and the on-line documentation linked above, if you're curious.

However, the vast majority of form validation can be done with a few simple things:

Here's a demonstration. (Note that I didn't re-use the input names from the earlier example because the JavaScript code above referred to the inputs by name, and so we need to make those unique. I could also have used a nested selector and given each form its own ID.)

<form action="/cgi-bin/dump.cgi">
  <p>Username: <input required name="username">
  <select required name="hogwarts_house">
    <option value="">Hogwarts House</option>   
    <option>Gryffindor</option>
    <option>Hufflepuff</option>
    <option>Ravenclaw</option>
    <option>Slytherin</option>
  </select>
  <p>Email address: <input required name="email" type="email">
  <p>Birthday: <input required name="birthday" type="date">
  <p><input type="submit" value="submit form">
</form>

Here's the actual form, so you can change the values of inputs:

Username:

Email address:

Birthday:

Try to submit an incomplete form!

Additional Material

You can stop here. The following information is just for those interested in learning more.

TBD

Radio Buttons

Important: Radio and checkbox input items should all have the same name, so that they are considered as related. (Our radio buttons on the pizza form were all named size.) Without the same name, radio buttons will not be mutually exclusive.
Tag Name Rendered Tag More Info
<input type=radio> Small Small
<input type=checkbox> Bacon Bacon

Checkboxes

Fieldset and Legend

There are additional elements related to a form, that we saw in the example above, such as label and legend, who are used for accessibility, or fieldset to group together elements in a form. By default, the browser will draw a box around all the elements in a fieldset (as we saw in the unstyled form).

Access Keys