Exploring HTML and XHTML

HTML has been around for a while now, and it has been continuously changing. Ideas that were once cutting edge (like using frames) are now considered out of date. HTML began as a very simple language, which became more complex as it was used more. HTML5 tries to make HTML simple again. The following ideas have driven the development of HTML5.

check.png Make the code as clean as possible. Things will get complicated fast. HTML code should be clean and easy to read. It shouldn’t have any unnecessary features, and it should be formatted in a way that is easy to follow.

check.png Separate structure from design. Try to keep your HTML code focused on the structure of the code (what it means) rather than the display (how it looks). This keeps the HTML code relatively clean and easy to work with.

check.png Use HTML for structure. Avoid tags like <font> and <center> in your HTML code, as they are difficult to change with JavaScript, clutter up your code, and are not allowed in some forms of HTML. Use HTML code to determine the meaning and structure of the page.

check.png Use CSS for design. You can keep the HTML a lot easier to work with if you leave the design work (colors, fonts, positions, and so on) to CSS. If you use CSS for design, your JavaScript will have a lot more ability to change how the page works because you can also modify CSS through JavaScript.

check.png Avoid use of tables and frames for layout. These techniques were the best tools Web designers had at one point, and so they were frequently used to provide visual structure to Web pages. However, modern CSS approaches provide for much cleaner code that’s easier to work with even when things get more advanced.

check.png Start with valid code. A lot of times, a page will look perfectly fine, but there will be some mistake hidden away that will rear its ugly head at the worst possible time (usually when you’re trying to show something to a client). It’s best to start your projects with HTML that you know is valid. See “Validating Your Pages,” later in this part, for more on ensuring the HTML foundation is in tip-top shape.

Appreciating HTML

HTML 4 was the dominant form of HTML for a long time. It was popular for some very good reasons:

check.png Universal support: By the time HTML 4 came out, there was really only one dominant browser — Internet Explorer 6 (IE6). Since the vast majority of users had some form of this browser, any code that would work for this browser was considered standard. In fact, the standards we call HTML 4 are really the parts of HTML 4 that were supported by IE6.

check.png Reasonable control: HTML 4 enhanced older versions of HTML with some nice features like font support, the ability to change colors, and some support for multimedia. Frames added a certain amount of layout support, although they brought their own problems.

check.png Ease of use: The HTML 4 standard itself was pretty easy to learn. It wasn’t too much trouble until you tried to do advanced stuff like table-based layouts. Then the simplicity of the language began to hurt because it just couldn’t do some things.

check.png Forgiving: HTML was designed to be very easygoing. If you did something wrong, the browser would simply guess what you were trying to say. Often, the guesses were correct.

Emergence of XHTML

HTML 4 was popular for a long time, but it wasn’t perfect. As Web development moved from a hobby enterprise to become the foundation of serious applications, the weaknesses of HTML 4 became more apparent. While HTML 4 never died away, a new standard called XHTML (eXtensible HyperText Markup Language) emerged among elite Web developers. XHTML was intended as a more serious answer to HTML 4. While HTML 4 was easy to get along with, it was considered sloppy by professional programmers. XHTML (especially the strict version) was much more precise and predictable, making it popular among higher-end developers. Here are the key features of XHTML Strict:

check.png More demanding syntax: XHTML is case-sensitive, it requires all attributes to be encased in quotes, and it has very strict rules for how tags are nested. Every tag must have an explicit closing tag. (Even one-off tags like <img> require a special closing character.) This more precise syntax made XHTML a little more exacting to program than HTML 4, but the results were far more predictable.

check.png Validation support: The main advantage of all the strictness in XHTML was support for validation. The HTML 4 standard was so loosey-goosey that nobody could tell if a page was formatted incorrectly. With XHTML, it became possible to run a special validation program that could find structural errors in your code.

check.png Separation of content and layout: HTML was originally intended only to describe the content of a document. By the time HTML 4 came out, it added numerous tags for handling the visual aspects of a document. The <font> and <center> tags were prime examples of this. While these tags did their jobs, they did not provide enough control, and moved away from the central idea of HTML. XHTML strict removed all layout tags.

check.png Rising importance of CSS: Cascading Style Sheets (CSS) were available in HTML 4, but they were not always used properly because HTML provided some alternatives. When XHTML eliminated layout tags, CSS moved from an optional enhancement to a central part of Web development.

check.png XML syntax: Early promoters of XHTML emphasized that XHTML followed the syntax of the XML standard. While this is true, it never turned out to be quite as important as people thought it might. The XML syntax made it easier for automated programs to manipulate Web pages as data, but that’s not a feature that most Web developers are terribly concerned about.

It’s alive, and it’s HTML5!

XHTML Strict was a really great idea, but it never really caught on. Professional developers (especially those who were integrating programming languages like JavaScript and PHP into their web projects) loved XHTML Strict. Top designers enjoyed the newfound freedom of CSS. However, XHTML was a little too unforgiving for most developers, and the vast majority of pages never bothered to validate to the new standards. When the time came to devise a new standard, the W3C finally decided to support HTML5 rather than XHTML 2.

HTML5 is not really a rejection of XHTML. It has some of the best features of both HTML 4 and XHTML:

check.png Simple doctype: The doctype definition (the boilerplate code that begins every Web page) for XHTML was really complicated. Even people who taught classes and wrote books about it (like, um, me) never memorized the doctype, but had to copy and paste it every time. HTML5 has a very simple and clean document definition, and it’s once again possible to write a page with a text editor from memory.

check.png Separation of content and style: HTML5 does not include the style tags from HTML 4 (font, center, and so on), requiring developers to use CSS for all styling. Likewise, frames and table-based layout are discouraged in favor of CSS-style layout.

check.png Validation support: Validation turned out to be a very useful tool, so HTML5 can be validated just like XHTML. The W3C validator (http://validator.w3.org; see “Validating Your Pages” later in this part) supports HTML5 now, and other validation tools are coming online. Validation is an easy way to eliminate goofy coding mistakes, and can greatly simplify your coding once you start adding programming support to your documents.

check.png Strict tradition: The coding standards of HTML5 are more like XHTML than HTML 4. While it’s still possible to use sloppy coding in HTML5, most developers use the XHTML strict standards to make the code easier to read and more predictable.

tip.eps All the code in this book adheres to the stricter style standards of XHTML.

check.png Tighter integration of CSS and programming languages: Perhaps the most important feature of HTML5 is its humility. While HTML is still the central language of the Internet, HTML5 is really about distributing control to other languages. HTML5 is designed as a central glue that ties together many other technologies: CSS for visual layout, JavaScript for client-side programming, server-side languages like PHP for server control, and databases.

check.png New capabilities: Of course, HTML5 presents new capabilities, which are the primary focus of this book. Many of the new features are not technically HTML but advances in the various other related technologies (integrated databases, new JavaScript syntax, new CSS features, and so on).

Setting up a basic HTML page

The basic HTML5 page is quite easy to build. Just open up any text editor and add the following code:

<!DOCTYPE HTML>

<html lang = “en”>

<head>

  <!-- basic.html -->

  <title>basic.html</title>

  <meta charset = ”UTF-8” />

</head>

<body>

  <h1>Level One Headline</h1>

  <p>

    This is a paragraph.

    Note that the text is automatically wrapped.

  </p>

  

</body>

</html>

This page, shown in Figure 2-1, is not difficult to create:

tip.eps I tend to bump up the font sizes in these screenshots when I can — doing so makes the page a bit easier to read. Be sure to look at the actual page on the Web site (www.aharrisbooks.net) to see exactly how it works.

Figure 2-1

9781118012529-fg0201.eps

To build a basic HTML5 page, follow these steps:

1. Begin with the doctype. Modern versions of HTML (XHTML and HTML5) have a special attribute called the doctype, which indicates which form of HTML is being used. The doctype for XHTML was extremely confusing, and HTML 4 didn’t have a doctype at all. Set the doctype to HTML5 with this tag: <!DOCTYPE HTML>. The doctype definition should be on the first line of your Web site. If you leave this out, you will still probably be able to use HTML5 features, but validators will have to guess about which form of HTML you’re using. (Consult any science fiction movie to see what happens when computers make guesses about things.)

2. Add the <html> tag. This special tag indicates the beginning of a Web page. It’s best to indicate which language the page is written in. Specify lang = “en” for English. Be sure to have a corresponding </html> tag at the bottom of the page. This indicates the end of the page you began with the <html> tag at the beginning of the page.

3. Create a <head> area. The head is something like the engine compartment of a car. People don’t usually go there, but there’s lots of important machinery. The head is empty in this simple example, but it will fill up with JavaScript and CSS goodness soon enough.

4. Specify the character set. While this isn’t strictly necessary, it’s considered good form to let the browser know what kind of characters to use when displaying your page. Pages written in English should generally use UTF-8, so indicate this with the following code: <meta charset = “UTF-8” />.

5. Indent your code. Browsers don’t care if your code is indented, but it’s a very good habit to get into. Generally, I indent every time I open a new element that isn’t closed on the same line. Then it’s easy for me to line up my beginning and ending tags to ensure the page is well formed and I didn’t miss any ending tags.

6. Add a comment. Comments aren’t strictly required, but they’re very good form. HTML comments begin with <!-- and end with -->. Typically the comments in this book will be a brief summary of the purpose of the page. Comments can last over several lines.

7. Put in a title with <title></title>. This tag allows you to specify a title for your page. The title typically appears in the Web browser’s title bar, and will also often appear in search engine results for your page. In this book, I generally put the filename in the title, so you can easily match the programs on the book’s companion Web site with those in the book code listings.

8. Include the bulk of the page in the <body> tags. If the head area is the engine compartment, the body is the passenger space. Most of the text that’s visible on the Web site is part of the body. The </body> tag is usually right before the </html> tag, as you’ll typically finish off the body and then close off the HTML.

9. Use heading tags to describe your outline. The <h1> tag is an example of a heading. The heading tags all begin with h followed by a number indicating the strength of the heading. All your main topics should be denoted by level-one headings. Subtopics should be level-two headings (<h2>). The heading levels go all the way to h6, but it’s unusual to use anything smaller than level 3.

10. Place most of the text into paragraphs. Although HTML doesn’t require use of paragraph tags, they’re still a very good idea. Place every paragraph inside a <p></p> pair. This will make it much easier to manage the look and behavior of your text later.

11. Save your file with the .html extension. Be sure to save the file with a .html extension. You can then load the file into a browser to see how it looks.

Remember.eps Some of these elements (especially the headings) will tend to have a particular visual style. The default styles are just there as guidelines. Avoid the temptation to pick headings based on their appearance. When you use CSS in Part 5, you’ll be able to make any heading look however you want.

Fleshing Out Your Page

If you’ve used HTML 4 or XHTML, you’ll find HTML5 very familiar. Most of your text will go into paragraphs, marked with the <p></p> pair. Larger sections may be enclosed in divisions, using the <div></div> pair. You’ll then add various other elements: images, links, lists, tables, and forms. HTML5 adds a few new elements, but for now, stick with the base that works in every browser.

Adding images

Web pages are capable of far more than text. Figure 2-2 shows a page with an embedded image.

Figure 2-2

9781118012529-fg0202.eps

Images are pretty easy to add to Web pages. Here’s the code for adding the image:

<!DOCTYPE HTML>

<html lang = “en”>

<head>

  <title>imageDemo.html</title>

  <meta charset = ”UTF-8” />

</head>

<body>

  <h1>Image Demo</h1>

  <p>

    <img src = “monkey.png“

         alt = “Picture of a happy monkey“ />

  </p>

  <h2>This page has a picture of a monkey</h2>

  <p>

    This monkey is called ‘Suzanne.‘ It‘s a default

    object in an incredible free 3D modeling tool

    called ‘Blender.‘

  </p>

</body>

</html>

Adding an image is relatively easy. Here’s what you do:

1. Identify the image you want to use. Of course, you have to have access to an image before you can use it. Be sure you have permission to use the image in your site.

2. Modify the image if necessary. You may need to adjust the image for use on the page. It’s best to resize your images before you use them on the Web. You can use commercial image-manipulation software, but I prefer IrfanView or Gimp for this kind of work. Links to both of these free programs are available on my Web site (www.aharrisbooks.net/h5qr/resources.html).

3. Choose your image type. Web browsers can display .jpg, .gif, and .png images. If your image is in another format, use a tool like IrfanView or Gimp to change it to one of these Web-friendly formats.

4. Put your image in the right place. The image file should be in the same directory as the HTML file. That way, when you post your page to the server, it will be easy to move the image as well.

5. Build your page as normal. The image will be placed with a tag embedded into the body.

6. Use the <img> tag to indicate the image. This tag needs to be embedded inside a paragraph or div if you want the page to validate correctly.

7. Use the src attribute to indicate the file containing the image. If the image file is in the same directory as the Web page, all you need is the name of the image. If the image file is elsewhere on the Internet, you can use a complete URL like http://www.aharrisbooks.net/jad/jad_2/monkey.png.

8. Include the alt attribute describing the image. The alt attribute contains text describing the image. This is important for those who cannot see your image — users with visual impairments, people who have turned off images to increase browsing speed, and search engine bots, which can’t see the images but read alt tags.

9. End the image tag with a /. The img tag is a special tag that doesn’t require (or allow) an end tag. The slash character at the end of the tag indicates that the tag is a one-shot tag that serves as its own ending tag.

Including links

The H in HTML stands for hypertext, which is a fancy term for links. Links are one of the things that make the Internet so cool and powerful. It’s very easy to add a link to a Web page. Figure 2-3 shows an example with two different kinds of links in it.

Figure 2-3

9781118012529-fg0203.eps

The code for building the links is reproduced here:

<!DOCTYPE HTML>

<html lang = “en”>

<head>

  <title>linkDemo.html</title>

  <meta charset = ”UTF-8” />

</head>

  <body>

    <h1>Link Demo</h1>

    <h2>Relative reference to an image</h2>

    <p>

      This paragraph has a link to a

      <a href = ”monkey.png”>monkey picture.</a>

    </p>

    

    <h2>Absolute reference to a web page</h2>

    <p>

      This paragraph contains a link to

      <a href = ”http://www.aharrisbooks.net”>

        Andy’s main site.

      </a>

    </p>

  </body>

</html>

Links are more than they appear. They display text on the page, but when the user clicks the text, the browser loads a different page on the Internet. Building links into your pages is quite straightforward.

1. Begin with an ordinary page. Links are usually embedded directly into your page. Links cannot stand on their own, but are usually part of some other block-level element like a paragraph.

2. Use the <a> tag to indicate a link. The a stands for anchor. (I know; it should be the link tag, but that term is used for something else in HTML.)

3. Utilize the href attribute to describe where the link will go. Most links have an href (hypertext reference) attribute, which describes what page should load when the user clicks the link. The href can be a relative or absolute address.

Relative: The href can be a simple filename. If you are linking to a file in the same directory as the Web page you’re writing, you can simply indicate the filename. This is known as a relative reference because the browser assumes the linked file is in the current directory of the current server. The first link of my example points to the monkey image in the same directory as the page itself.

Absolute: The href can also be a complete Web address. If you prefer, you can give the entire address of a Web site. This is known as an absolute reference because it explains how to find the file regardless of the location of the current page. If you want to point to pages or files on somebody else’s server, you must use absolute references.

4. Place the visible text between the <a> and </a> tags. Any text that appears between the <a> and the </a> tags will be displayed on the screen in a format that indicates a link. The default format is blue underlined text. You find out how to change that (and many other display tricks) in Part 5.

The file you link to can be a Web page or anything else the browser can read. The first link on linkDemo.html points to an image file, and the second points to a Web page. Most links point to Web sites, but you can also link anything the browser can read, including images.

Making lists and tables

Pages are often about data, and data is often organized into lists. Figure 2-4 illustrates a page with a series of lists on it.

Figure 2-4

9781118012529-fg0204.eps

The page in Figure 2-4 shows two main types of lists and a combination list that nests one type into another. Here’s the code used to create the lists:

<!DOCTYPE HTML>

<html lang = “en”>

<head>

  <title>listDemo.html</title>

  <meta charset = “UTF-8” />

</head>

<body>

  <h2>Languages</h2>

  <ul>

    <li>English</li>

    <li>Spanish</li>

    <li>Japanese</li>

  </ul>

  

  <h2>Counting in English</h2>

  <ol>

    <li>one</li>

    <li>two</li>

    <li>three</li>

  </ol>

  

  <h2>Counting in Other Languages</h2>

  <ul>

    <li>Spanish

      <ol>

        <li>uno</li>

        <li>dos</li>

        <li>tres</li>

      </ol>

    </li>

    

    <li>Japanese

      <ol>

        <li>ichi</li>

        <li>ni</li>

        <li>san</li>

      </ol>      

    </li>

  </ul>

</body>

</html>

Lists, like most HTML elements, are quite easy to build.

1. Designate the beginning of the list with <ul> or <ol>. The <ul> tag indicates an unordered (bullet) list, and the <ol> tag is used to describe an ordered (numbered) list. When you use CSS (described in Part 5) to style your lists, you can have many different kinds of marking, including numbers, Roman numerals, bullets, or custom graphics.

2. Mark each item with an <li></li> pair. The <li> tag is used to indicate a list item. All elements of a list should be enclosed in the <li> tag.

3. (Optional) Nest lists inside each other. The <li> of one list can contain an entire new list. This is the technique used to build the nested lists in the example. Just be sure to close off one list before beginning a new one. Proper indentation helps you keep track of how deeply you’re nested.

Utilizing tables

Sometimes you will encounter data that is best presented in a tabular format. HTML has a full-featured table system for exactly this purpose. For example, consider the table displayed in Figure 2-5.

Figure 2-5

9781118012529-fg0205.eps

The basic structure of a table in HTML format is reasonably easy to understand. Here’s the code that created basicTable.html:

<!DOCTYPE HTML>

<html lang = “en”>

  <head>

    <title>basicTable.html</title>

    <meta charset = “UTF-8” />

    <style type = “text/css”>

    table, td, th {

      border: 1px solid black;

    }

    </style>

  </head>

  

  <body>

    <h1>A Basic Table</h1>

    <h2>HTML Superheroes</h2>

    <table>

      <tr>

        <th>Hero</th>

        <th>Power</th>

        <th>Nemesis</th>

      </tr>

    

      <tr>

        <td>The XMLator</td>

        <td>Standards compliance</td>

        <td>Sloppy Code Boy</td>

      </tr>

    

      <tr>

        <td>Captain CSS</td>

        <td>Superlayout</td>

        <td>Lord Deprecated</td>

      </tr>

    

      <tr>

        <td>Browser Woman</td>

        <td>Megacompatibility</td>

        <td>Ugly Code Monster</td>

      </tr>

    

    </table>

  </body>

</html>

When you examine this code, you can see that a table is simply a set of carefully nested tags. The process for building a table is not difficult, but it does require some forethought.

1. Plan your table first. It’s much easier to build a table in HTML if you already know how it will be structured. You should know how many columns you will have, and which rows or columns will be headlines. It’s a good idea to sketch out your table on paper if you’re not sure of these things.

2. Begin the table with the <table> tag. The <table></table> pair encloses the entire table.

3. Create a table row with <tr>. The table is defined with a series of rows. Use the <tr></tr> pair to enclose each row of data.

4. Signify headings with <th>. Some cells will contain headings, and some will contain actual data. Often, the top row will contain headings (sometimes the left-most column will, too). Use the <th></th> pair to signify text that should be treated as a heading cell. By default, such cells are generally bolder and centered, but that can be changed with CSS.

5. Specify ordinary data cells with <td>. The <td></td> pair is used to specify an ordinary data cell. Most of the cells in your table will be specified by td tags.

6. Keep the number of cells consistent. Each row should have the same number of cells. (Although there are techniques that allow you to extend a cell across multiple rows or columns, I stick to basic techniques in this introductory part.)

7. Add CSS as needed. Tables do have a basic format, but as usual, you can change things with CSS. I added borders to this example, so it’s easier to see the table in Figure 2-5.

8. Do not use tables for layout. The early versions of HTML did not have adequate support for layout (creating columns and precise page layout). Clever HTML developers came up with all sorts of hacks using tables to simulate a layout system. CSS (covered in Parts 5 and 6) provides all the page layout techniques you need, so use of tables should be restricted to its original purpose: presenting tabular data.

Making a Form

From the beginning, Web pages have had the ability to gather data from users. HTML has a standard but quite useful set of form elements that you can use to get input. You can’t do anything with the data in plain HTML, but that’s what JavaScript and PHP are for. You’ll write a number of programs to extract data from Web forms, so it’s a good idea to know how they work. Figure 2-6 shows a form containing all the main HTML form elements you might encounter.

Figure 2-6

9781118012529-fg0206.eps

The page in Figure 2-6 has a lot of code on it compared to the earlier examples in this part. I show you the entire code here so you can see how it fits together, and then I explain how the various parts work.

<!DOCTYPE HTML>

<html lang = “en”>

  <head>

    <title>formDemo.html</title>

    <meta charset = ”UTF-8” />

  </head>

  <body>

    <h1>Form Demo</h1>

    <form>

      <fieldset>

        <legend>Text input</legend>

        <p>

          <label>Text box</label>

          <input type = “text“

                 id = “myText“

                 value = “text here“ />

        </p>

        <p>

          <label>Password</label>

          <input type = password“

                 id = myPwd“

                 value = secret“ />

        </p>

    

        <p>

          <label>Text Area</label>

          <textarea id = myTextArea“

                rows = 3“

                cols = 80“>Your text here</textarea>

        </p>

      </fieldset>

      

      <fieldset>

        <legend>Selecting elements</legend>

        <p>

          <label>Select List</label>

     

          <select id = myList“>

            <option value = 1“>one</option>

            <option value = 2“>two</option>

            <option value = 3“>three</option>

            <option value = 4“>four</option>

          </select>

        </p>

    

        <p>

          <label>Check boxes</label>

           <input type = checkbox“

                 id = chkEggs“

                 value = greenEggs“ />

           <label for = “chkEggs“>Green Eggs</label>

           

          <input type = “checkbox“

                 id = “chkHam“

                 value = “ham” />

          <label for = “chkHam”>Ham</label>

        </p>

        <p>

          <label>Radio buttons</label>            

          <input type = ”radio”

                 name = ”radSize”

                 id = ”sizeSmall”

                 value = ”small”

                 checked = ”checked” />

          <label for = ”sizeSmall”>small</label>

          

          <input type = ”radio”

                 name = ”radSize”

                 id = ”sizeMed”

                 value = ”medium” />

          <label for = ”sizeMed”>medium</label>

          <input type = ”radio”

                 name = ”radSize”

                 id = ”sizeLarge”

                 value = ”large” />

          <label for = ”sizeLarge”>large</label>

        </p>

      </fieldset>

      

      <fieldset>

        <legend>Buttons</legend>

        <p>

          <button type = ”button”>

            standard button

          </button>

          

          <input type = ”button”

                 value = ”input button” />

          <input type = ”reset” />

          <input type = ”submit” />

        </p>       

      </fieldset>     

    </form>

  </body>

</html>

As you can see, form elements follow many of the same rules as the tags you’ve already seen, but there are some differences.

tip.eps The form elements shown in this example are available in all current versions of HTML. See Part 4 for information on new form elements available in HTML5.

Form structure tags

These tags are used to help manage the general structure of the form:

check.png <form>: The <form> tag is the actual tag containing the form. All the form elements are enclosed inside this tag. The <form> tag should also include the action = “” attribute. This indicates that you do not plan to call a server-side script when the form is submitted.

check.png <fieldset>: This is a special tag that allows you to group a series of input elements together. It is not required, but it can make complex forms easier to navigate. By default, a fieldset has a single border around it, but you can change this with CSS.

check.png <legend>: A legend can be added to a fieldset. It acts as a label for the entire fieldset.

check.png <label>: The <label> tag marks text as the label associated with a particular input element. You can use the optional for attribute to specify which input element the label is associated with. Label tags are normally used to make CSS styling of forms easier to manage.

tip.eps The fieldset, legend, and label tags are not required, and frankly, they weren’t used much in earlier forms of HTML. These tags are used more commonly in XHTML and HTML5, where use of tables to organize the physical layout of the page is discouraged. These tags help you organize the page so it’s easier to lay out with CSS. Proper use of these tags and CSS often makes your forms much easier to work with than the older table-based hacks.

Constructing text input

Many of the form elements are based on the input tag. This workhorse is a general-purpose tag used to make a number of interesting input objects. The type attribute is used to determine what type of element the tag creates on the page. By far, the most common input element is the basic text box. Its code looks like this:

          <input type = “text”

                 id = “myText”

                 value = “text here” />

Building it is straightforward.

1. Create an input element. The <input> tag creates the general structure of the element.

2. Set the type to “text”. This indicates you are building a standard text element, not something more elaborate.

3. Add an id attribute. The id attribute allows you to name the element. This will be very important when you add JavaScript to the page because your JavaScript code will use the ID to extract data from the form.

4. Add default data. You can add default data if you want, using the value attribute. Any text you place in the value will become the default value of the form.

The text element will place a small box on the screen. When the user selects the box, the cursor will change to an I-beam, and the user will be able to type text into the box.

Of course, if you want to do something with this text, you’ll need to write some code. See Bonus Part 1 for information on using JavaScript to read data from forms.

Creating password fields

The standard input element has a cousin that is sometimes used — password. The code for the password looks a lot like the code for a standard input element.

          <input type = “password”

                 id = “myPwd”

                 value = “secret” />

The password field looks very similar to the ordinary text field, but it does have one primary difference. When the user types data into the text field, the actual contents of the field are replaced by asterisks. This prevents evil henchmen from looking over your shoulders to discover your password.

Warning.eps The password field doesn’t provide any real security to speak of. When it is used to send a request to a Web server, that request is normally sent in the clear, where those evil henchmen are sure to find it. In JavaScript processing, the situation is even worse because the code used to retrieve the data will be freely available to the browser. JavaScript is not the language to use if you want to keep a lot of secrets.

Erecting a multiline text box

Sometimes you’ll need the ability to enter several lines of text. The text area element is perfect for this situation. Its syntax is a bit different from the input element you’ve seen so far:

          <textarea id = “myTextArea”

                rows = “3”

                cols = “80”>Your text here</textarea>

To make your own text area:

1. Begin with the <textarea> tag. This tag indicates the beginning of a multiline text box.

2. Specify the number of rows. Indicate the number of rows (or lines) of text you want the text area to contain. Larger boxes accommodate more text but require more room on the screen.

3. Indicate the number of columns. The number of columns shows how wide (in characters) the text box should be. 80 characters is typical for a page-width form.

Forming drop-down lists

Drop-down lists are a common feature in Web pages. They are nice because they allow the programmer to specify a number of choices. The user can choose a selection without typing. Drop-down lists are especially nice because they don’t require a lot of screen real estate — the options are visible only while the user is selecting them.

Drop-down lists have one more incredibly important attribute; they prevent certain kinds of errors. The limited options make the response very predictable. When you allow the user to type information into a form, it can be very difficult to check for all the crazy things the user might enter. With a list box, you’ve already predetermined all the possible answers. There’s a lot less that can go wrong.

In HTML/XHTML, drop-down lists are created by two types of object. The overall structure uses the <select> tags, while each of the possible choices has its own <option> tag. Here’s how it works:

          <select id = “myList”>

            <option value = “1”>one</option>

            <option value = “2”>two</option>

            <option value = “3”>three</option>

            <option value = “4”>four</option>

          </select>

The select list is a real powerhouse, so you should know how to make it:

1. Create the <select> element first. The container for the list will be a <select> element. The entire list is encased in the <select></select> pair.

2. Give the select element an ID. You’ll use this ID to refer to the element in code.

3. Add an option element to the select element. I normally indent the options to remind myself they are part of the select object.

4. Give each option a value. The value will be the response sent to a program when the user chooses an option. The user will not necessarily see the value.

5. Indicate the text the user will see. The text that the user will see for the option goes between the <option> and </option> tags. This can be different from the value, or the same. (That will make more sense after you do some JavaScript coding.)

6. Add as many options as you want. Create a new option object for each choice you want to have available in the list.

tip.eps Select boxes don’t have to have the drop-down behavior. If you want the box to take up more vertical space on the page, just specify the number of rows with the size attribute.

Making checkboxes

Sometimes you’ll have some kind of information that can be true or false. The checkbox element is perfect for this kind of input because the user can click to select or deselect the option. Checkboxes are another variant of the versatile input tag:

        <p>

          <label>Check boxes</label>

           <input type = “checkbox”

                 id = “chkEggs”

                 value = “greenEggs” />

           <label for = “chkEggs”>Green Eggs</label>

           

          <input type = “checkbox”

                 id = “chkHam”

                 value = “ham” />

          <label for = “chkHam”>Ham</label>

        </p>

When you build a checkbox, you’ll typically also attach a label to the text box. This way, the user can click the checkbox or the associated label to make a selection. Checkboxes often appear in groups, but they are independent of each other. Here’s how to build a checkbox:

1. Begin with an input element. Checkboxes are just another form of the input element.

2. Set the type attribute to checkbox. This clarifies that the input element will be a checkbox. A small checkable box will be placed on the screen.

3. Give the element an id. Like all form elements, you’ll need an id field so that your code can work directly with the element.

4. Specify a value. You can attach a value to a checkbox. The user won’t see the value (unless you choose to make the label look just like the value).

5. Add a label. Checkboxes really need to have a label associated with them so that the user will understand what the checkbox is about. The label of a checkbox is usually applied to the right of the checkbox.

6. Add the for attribute to the label. The label has a special attribute called for, which allows you to specify which input element the label corresponds to. Place the id value of the checkbox into this attribute of the label. This is especially useful for checkboxes because in most browsers the user can click either the label or the checkbox to trigger the selection. Associating the label to the checkbox gives the user a larger target to click on, and makes the form easier to use.

tip.eps HTML forms don’t do anything on their own. You’ll need to add some sort of programming in JavaScript or HTML to make the form do something.

Popping in radio buttons

On the surface, radio buttons seem a lot like checkboxes, but they are different in a number of important ways.

check.png Radio buttons occur only in groups. You can have one checkbox on a form, but radio buttons make sense only when they are placed in groups.

check.png One element of a radio group is selected. In a radio button group, selecting one button deselects the others. It’s like a car radio, where clicking one of the preset buttons deselects the others. (It’s really like the old car radios where if the selected station was physically pushed in, the others would pop out. I’m not going to mention that, though, because it would make me seem old.)

check.png There should always be one element selected. When you build a radio group, you should always make one element of the group selected. If not, any programs attached to your form will get confused.

check.png The id of each radio button is still unique. Each id on a Web page must be unique, and the id elements of each radio button will follow the same rules as usual.

check.png Each radio element also has a name attribute. The name attribute is used to specify the entire group of radio objects.

check.png All radio buttons in a group have the same name. HTML uses the name attribute to figure out which group a radio button is in, and to ensure that only one button in a group is selected.

Building a radio group is quite similar to creating checkboxes, but there are a few differences.

1. Begin by creating an input element. As usual, the input element provides the basic foundation.

2. Set the type to radio. Use the type attribute to form radio buttons.

3. Give each element a unique id. As usual, apply a unique id to each radio button.

4. Give all buttons in a group the same name. Use the name attribute to identify the buttons in a group.

5. Consider visual grouping as well. The user won’t be able to tell which buttons are part of a group by the HTML formatting alone. It might be best to use fieldsets or other formatting tricks to help the user know which buttons are in which group. All buttons in one group should be physically near each other.

6. Make one of the buttons checked (selected) by default. Apply the checked = “checked” attribute (provided by the department of redundancy department) to one of the elements so it will start out checked.

Putting in action buttons

One more critical form element is the ubiquitous button. Buttons are great because they just sit there looking irresistible. Users normally expect something important to happen when they click a button. There are actually three main types of buttons, although they all look identical to the user.

check.png Standard button: A standard button just looks like a button. These buttons are usually used in JavaScript programming to trigger some kind of action on the client end. You use this type of button a lot in JavaScript.

check.png Submit button: This button is normally used in server-side programming. It packages up all the data in the form and submits it to a program that lives on a remote Web server.

check.png Reset button: This special button type has built-in behavior. When the user clicks a reset button, all the data in the form is reset to its original default values.

In addition to the three types of buttons, button elements can be created in two different ways. The amazing input element can be used to build a button as well, like this:

          <input type = “button”

                 value = “input button” />

When used in this way, the value property becomes the label of the button, and the type property indicates which type of button you intend to build. It isn’t necessary to add a label to a button because the label is implied.

This is the original way buttons were created in HTML, and it’s still commonly used. But buttons aren’t really used for input; they’re used to specify that the user wants to do something. For that reason, a new button syntax has evolved:

          <button type = “button”>

            standard button

          </button>

This syntax introduces a button tag with start and end tags. The type attribute is used to indicate which type of button you want to use. (The default type is “submit,” used primarily in server-side development, which is not the focus of this book.) The text inside the button indicates the text printed on the button. I tend to use the button syntax because I think it’s cleaner, and also because it makes CSS formatting (see Part 5) a bit easier, as buttons are rarely formatted in the same way as other input elements.

Validating Your Pages

The guidelines described in this part will generally give you a decent Web site, but if you’re like me, you’ll still make sloppy mistakes sometimes. It would be great if you had some sort of tool that acted like a spell-checker for code. It could look for dumb mistakes like missing tags and stuff that’s out of order. Sometimes you’ll have junk like that in your code, and you won’t even know it’s a problem. It may look fine on your browser, but mistakes like this have a habit of appearing when you’re hooked up to a projector showing hundreds of people how to build Web sites. (Well, maybe that’s just me. . . .)

Fortunately, there is exactly such a code-checker available. The W3 consortium (the same guys who came up with the standards in the first place) have provided a software tool that allows you to check any page to see if it complies with the standards you’ve declared in the doctype. This tool is called the W3 validator, and it’s available at this cleverly named address:

http://validator.w3.org

Figure 2-7 shows a page being checked by the W3 validator.

The validator is great, but it’s not perfect. It can’t find every mistake, and of course it works only when you’re connected to the Internet. More troubling, the error messages it gives you are sometimes very mysterious and not very helpful.

tip.eps The W3 validator checks XHTML and HTML5 code. As HTML5 becomes more common, watch for other tools to be available directly in your browser and editor to simplify validating HTML5 code.

Figure 2-7

9781118012529-fg0207.eps

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset