PHP, MySQL, JavaScript & HTML5 All-in-One For Dummies (2013)

Book II: HTML and CSS

Chapter 3: Creating and Styling Web Forms

In This Chapter

arrow.png Using web forms to get information

arrow.png Creating a form

arrow.png Using CSS to style a form

Web forms enable your site to gather information from users. This chapter discusses web forms in all their glory and shows you how to both create a form and how to style it with CSS.

Using Web Forms to Get Information

With web forms, like the one shown in Figure 3-1, you can gather information from users.

9781118213704-fg020301.eps

Figure 3-1: A basic web form.

Web forms can collect anything from name and e-mail address and a message, like the one shown in Figure 3-1, to images and files from your computer. For instance, when you log in to your web-based e-mail account like Gmail, you’re filling out a form with your username and your password. Here’s a look at how you can use HTML to create web forms.

Understanding web forms

When you fill out a form, the information is sent to the web server. What exactly the web server does with the information is up to the programs running on the server. For example, when you fill out the contact form on my website, the server e-mails the information e-mailed to me, but when you fill out a form to find hotel rooms on a hotel’s website, the server looks in its database for matching rooms based on the dates that you fill out. In Book VI, you work with server-side programs to process web forms. For now, focus on the forms themselves.

In HTML terms, forms are created with the <form> element. Forms open with <form> and close with </form>, as in this example:

<form action="#">

<input type="text" name="emailaddress">

<input type="submit" name="submit">

</form>

You see how to create your own form in the next section.

Looking at form elements

There are many ways to get input through a form, each with its own specific name or type of input. The code example in the preceding section includes two input types: a text type and a submit type. The text type creates a box where the users can enter information. The submit type creates a button that users use to send the information to the server.

There are many other types of input elements in a form, including these:

check Drop-down or select: Creates a drop-down box with multiple choices from which the user can pick one.

check Check boxes: Creates one or more boxes that the user can select.

check Radio buttons: Creates one or more small buttons, of which the user can select only one.

check Others: There are other specialty types — including password, text area, and file — that enable you to gather other types of input from the user.

You’ve already seen the basic form elements, but there’s more to creating forms than just adding elements. Forms need to be integrated with other HTML in order to display like you want them to. Beyond that, as you see later in the chapter, you can also style forms with Cascading Style Sheets (CSS). But for now, work on building a simple form.

Figure 3-2 shows a web form using two text input types.

9781118213704-fg020302.eps

Figure 3-2: A basic web form with two inputs.

The HTML used to create this form is shown here:

<!doctype html>

<html>

<head>

<title>A Basic Form</title>

</head>

<body>

<h1>A Basic Form</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Form Information</legend>

    <div>

        <label for="username">Name:</label>

        <input id="username" type="text" name="username">

    </div>

    <div>

        <label for="email">E-mail Address:</label>

        <input id="email" type="text" name="email">

    </div>

</fieldset>

</form>

</body>

</html>

Up until the first <form> tag, the HTML is all stuff you've already seen earlier in this book. The form begins with that opening <form> tag. When you create a form, you use two attributes fairly often, one of which is the action attribute. The action attribute tells the form where to go or what to do when the user clicks Submit. You see another attribute, method, a little later.

The next element found in the form is <fieldset>, which is optional for a form. The <fieldset> element is used primarily for layout and accessibility. The next element found is the <legend> element. This element creates the Form Information legend and the box that (though difficult to see in the screenshot) surrounds the inputs in the form. Like <fieldset>, the <legend> element is entirely optional.

Next in the form are the <div> elements used to create each row of inputs. The <label> element ties the friendly name — what you see on the screen, in this case, Name — to the actual input. The <label> element is optional but recommended because it helps with assistive technologies. Below the <label> element you see an <input> element. This <div>, <label>, <input> structure is repeated for the E-mail Address field.

Creating a Form

With some understanding of how forms are structured, it's time to look at creating one with some of the elements already discussed. In this section, you find out more about the <form> element and how to create text boxes, drop-down boxes, check boxes, and radio buttons that visitors to your website can use to enter information. You also find out how to create a Submit button, which lets visitors indicate that they're ready to transmit that information to you.

All about the form element

You already saw that the <form> element commonly uses a couple different attributes, action and method. The action of a form typically points to the server program that will handle the input from the form. It's where the form sends its data.

If the action tells the form where to send the data, then the method attribute tells the form how to send the data to the server. There are two primary methods that you'll encounter: GET and POST. The GET method is appropriate for small forms, whereas the POST method is appropriate for larger forms or ones that need to send a lot of information.


Knowing the difference in the GET and POST methods

When you use a GET method, the form's contents are sent as part of the URL. In the sample form that you saw earlier, the URL would end up being something like:

http://localhost/form1.html?username=Steve&email=steve@example.com

The first thing you notice is that a user can easily see all the form elements, including their names and values, right in their browser’s address bar. Beyond that, though, there’s a practical limitation in just how long that URL can get. Many browsers, like Internet Explorer, only allow a certain number of characters in the URL, so if your form or the data being sent is too long, then it won’t work.

When you use a POST, there's no such length restriction set by the browser. It's important to note, though, that the user can still see the form's data and how it will be sent to the server; you can't hide that from the user no matter which method you use.

For most forms, I use POST unless there's a specific reason to use the GET method.


When the action is set, as you’ve seen, to the pound sign or hash mark (#), the form essentially goes nowhere and does nothing, which for now is exactly what you want because you haven’t built a server program to work with the incoming data yet!

Adding a text input

You've already seen text inputs in this chapter. Adding one is as simple as using the type of "text". You can also add a couple more handy attributes, size and maxsize, which tell the browser how large to make the text box on the screen and the maximum amount of characters that are allowed in the field.

For example:

<input type="text" name="username" size="20" maxsize="30">

This HTML creates a 20-characters-wide input box, and the most that someone could enter into the box is 30 characters.

Another attribute that you might see is the value attribute, which prepopulates the field with the value you provide. Consider this example HTML:

<input type="text" name="username" value="Username Here">

Adding that to the form from Figure 3-2 results in a form like the one shown in Figure 3-3. Notice the value in the Name field is now set according to the value property in the <input> definition.

9781118213704-fg020303.eps

Figure 3-3: Adding a value to a field.

Adding a drop-down box

A drop-down box, also known as a select box, presents many options, from which the user can select one. An example is a list of states, such as Alaska, California, Wisconsin, and so on, where the user typically chooses one from among the list. The drop-down box provides a good way to display that information. You create a drop-down using the <select> element along with <option> elements, like this:

<select name="state">

    <option value="CA">California</option>

    <option value="WI">Wisconsin</option>

</select>

Here’s a full form with a drop-down added to it:

<!doctype html>

<html>

<head>

<title>A Basic Select</title>

</head>

<body>

<h1>A Basic Select</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Form Information</legend>

    <div>

        <label for="state">State:</label>

        <select id="state" name="state">

            <option value="CA">California</option>

            <option value="WI">Wisconsin</option>

        </select>

    </div>

</fieldset>

</form>

</body>

</html>

When it’s viewed in a browser, you get a page like that shown in Figure 3-4.

9781118213704-fg020304.eps

Figure 3-4: Creating a select drop-down box.

When a drop-down box is displayed, the first element is the one that shows up as the default. In the example shown in Figure 3-4, California is displayed as the default option. You can, however, change the default value in two different ways, as discussed here.

Like text boxes, you can set a default value for a drop-down box. This is accomplished using the selected attribute. Though not always required, it's a good idea to set a value for the selected attribute, as in this example that would change the default value to Wisconsin:

<select name="state">

    <option value="CA">California</option>

    <option selected="selected" value="WI">Wisconsin</option>

</select>

Another way to set a default value of sorts is to set a blank option as the first option in the list. While this isn't technically a default value, it shows up first on the list so it'll show as the default option when a user loads the page. A common way you'll see this is to use "Select a value" or similar wording as the first option, indicating to the user that there's some action required, as shown here and in Figure 3-5.

        <select name="state">

            <option value="">Select a value...</option>

            <option value="CA">California</option>

            <option value="WI">Wisconsin</option>

        </select>

9781118213704-fg020305.eps

Figure 3-5: Setting the first value for a drop-down.

tip.eps Using the selected attribute overrides the first value trick shown in this example.

Creating check boxes

Another way to represent multiple values is by using check boxes. Where drop-downs are good to represent multiple values when there are a lot of options, check boxes are good to represent multiple values when there are just a few options, as might be the case when building a form for choosing pizza toppings. When someone adds pizza toppings, she can choose more than one on her pizza, but there usually aren’t too many toppings.

<!doctype html>

<html>

<head>

<title>Checkboxes</title>

</head>

<body>

<h1>Checkboxes</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Pizza Information</legend>

    <div>Toppings: <br />

        <input type="checkbox" id="sausage"

          name="toppings" value="sausage">

        <label for="sausage">Sausage</label><br />

        <input type="checkbox" id="pep"

          name="toppings" value="pep">

        <label for="pep">Pepperoni</label><br />

        <input type="checkbox" id="mush"

          name="toppings" value="mush">

        <label for="mush">Mushrooms</label><br />

    </div>

</fieldset>

</form>

</body>

</html>

This HTML creates three check boxes in a group called "toppings". The resulting page is shown in Figure 3-6.

9781118213704-fg020306.eps

Figure 3-6: Using check boxes for input.

Notice in the HTML that each check box has the same name attribute but uses different value attributes and different id attributes. The id attributes need to be unique in order for the HTML to be valid (and for the labels to work correctly). The name is the same because the check boxes are actually grouped together; they represent one type of information: pizza toppings.

In practice, you may see check boxes without name attributes or with a different name attribute for each check box. The example you see here is one that keeps the information logically grouped, which makes it easier to maintain later and also makes it easier to work with in a server program, as you see later in this book.

Using radio buttons

Radio buttons are used where there are multiple values but the user can choose only one from among those options, as would be the case with a type of crust for a pizza. The crust can be thin or deep dish — but not both or the pizza would be a complete mess.

Here’s the HTML to create radio buttons. Notice that the HTML isn’t really all that much different than the check box example:

<!doctype html>

<html>

<head>

<title>Radio</title>

</head>

<body>

<h1>Radio</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Pizza Information</legend>

    <div>Crust: <br />

        <input type="radio" id="deep"

          name="crust" value="deep">

        <label for="deep">Deep Dish</label><br />

        <input type="radio" id="thin"

          name="crust" value="thin">

        <label for="thin">Thin</label><br />

    </div>

</fieldset>

</form>

</body>

</html>

When viewed in a browser, the result is like that in Figure 3-7.

Like check boxes, radio buttons have the same name but use different value and id attributes. Like check boxes, radio buttons use these values for the same reasons. With radio buttons, the name attribute is even more crucial. Radio buttons that share the same name attribute are in the same group, meaning the user can choose only one of the options in that group. If you want the user to be able to choose more than one option, then you should probably be using a check box.

tip.eps However, you can use more than one radio button group on a page. Just use a different name for the new radio button group and the user will be able to select from that group too.

9781118213704-fg020307.eps

Figure 3-7: Radio buttons on a web page.

Submitting and clearing the form

Thus far, you've seen some of the input types that you can use on a web page to gather information. The really big glaring piece missing from your knowledge is how to actually submit the form or send it to the server for processing. That's accomplished with another input type calledsubmit.

<input type="submit" name="submit"

                     value="Process Request">

For example, consider this example, where a Submit button is added to a form that you saw earlier in the chapter:

<!doctype html>

<html>

<head>

<title>A Basic Form</title>

</head>

<body>

<h1>A Basic Form</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Form Information</legend>

    <div>

        <label for="username">Name:</label>

        <input type="text" id="username" name="username">

    </div>

    <div>

        <label for="email">E-mail Address:</label>

        <input type="text" id="username" name="email">

    </div>

    <div>

        <input type="submit" name="submit"

                          value="Send Form">

    </div>

</fieldset>

</form>

</body>

</html>

This HTML results in a page like that in Figure 3-8.

9781118213704-fg020308.eps

Figure 3-8: Adding a Submit button.

Another button that you see on forms is a Clear or Reset button. The Reset button clears the input and resets the form, removing anything the user has placed into the form. Adding a Reset button is as simple as adding an input type of "reset":

<input type="reset" name="reset" value="Clear Form">

Using CSS to Align Form Fields

The form examples you’ve seen so far have been pretty boring, just plain HTML with no alignment or visual appeal. Forms are just standard HTML, so they can be styled using CSS. This section looks at how to do just that. The example you’ll see in this section uses CSS right within the HTML file. This is done for simplicity.

When aligning form fields, the key is to use well-structured HTML. The HTML that you've seen so far in this chapter fits the bill and so aligning the form fields will be rather easy. In fact, using the HTML from the final example as a guide, merely adding this style information to the<head> section aligns the fields:

<style type="text/css">

.form-field {

    clear: both;

    padding: 10px;

    width: 350px;

}

.form-field label {

    float: left;

    width: 150px;

    text-align: right;

}

.form-field input {

    float: right;

    width: 150px;

    text-align: left;

}

</style>

The result is shown in Figure 3-9. Each of the style rules match using a CSS class and, in the case of the label and input, a child selector is further used to narrow the application of the CSS rule.

9781118213704-fg020309.eps

Figure 3-9: Aligning form fields with CSS.

But wait! The Send Form button is now stretched to 150px wide and the text (“Send Form”) is aligned to the left side of the button. Oops, looks like that’s exactly what you asked for:

.form-field input {

    float: right;

    width: 150px;

    text-align: left;

}

You need a way to either make that button smaller or at the very least to align the text in the center of it. Steve personally likes bigger buttons. They make it easier for users to click or tap, if they’re using a mobile device. So we’re choosing to align the text in the center but leave the button the same size.

Aligning it in the center means adding something to the Submit button's HTML in order to be able to access it within the CSS. The easiest way to do that is by adding an id attribute to the Submit button, like so:

<input id="submit" type="submit" name="submit"

        value="Send Form">

Here’s the CSS to add:

#submit {

    text-align: center;

}

The result is shown in Figure 3-10.

9781118213704-fg020310.eps

Figure 3-10: Aligning the text of the Submit button.

The full HTML and CSS are shown here:

<!doctype html>

<html>

<head>

<title>A Basic Form</title>

<style type="text/css">

.form-field {

    clear: both;

    padding: 10px;

    width: 350px;

}

.form-field label {

    float: left;

    width: 150px;

    text-align: right;

}

.form-field input {

    float: right;

    width: 150px;

    text-align: left;

}

#submit {

    text-align: center;

}

</style>

</head>

<body>

<h1>A Basic Form</h1>

<hr>

<form action="#">

<fieldset>

    <legend>Form Information</legend>

    <div class="form-field">

        <label for="username">Name:</label>

        <input type="text" id="username" name="username">

    </div>

    <div class="form-field">

        <label for="email">E-mail Address:</label>

        <input type="text" id="username" name="email">

    </div>

    <div class="form-field">

        <input id="submit" type="submit" name="submit" value="Send Form">

    </div>

</fieldset>

</form>

</body>

</html>