Chapter 3 HTML Forms
Introducing Forms Let ’ s start by looking at a couple of examples of forms. The figure below shows you the Google homepage. This contains two kinds of form controls: A text input , which is where you enter your search term. Submit buttons , which are used to send the form to the server. There are two on this form: you can see the words “ Google Search ” written on the first one and “ I ’ m Feeling Lucky ” on the second.
Now let ’ s look at a more complicated example Now let ’ s look at a more complicated example. The following figure shows part of an form, which actually spreads over several pages. It shows many more types of form controls: Select boxes , sometimes referred to as drop - down lists, such as the one in the top left of figure to say how long you have been driving. Radio buttons , such as the ones in the top - right corner with Yes or No options. When you have a group of radio buttons, you can only pick one response. Checkboxes , such as the ones at the bottom of the screenshot indicating how you can be contacted (by e - mail, post, or phone). When you have a group of checkboxes, you can pick more than one response. Text inputs , to enter a date of birth and registration number.
Creating a Form with the < form > Element As you have already seen, forms live inside an element called < form > . The < form > element can also contain other markup, such as paragraphs, headings, and so on, although it may not contain another < form > element. Providing you keep your < form > elements separate from each other (and no < form > element contains another < form > element), your page may contain as many forms as you like. For example, you might have a login form, a search form, and a form to subscribe to a newsletter, all on the same page. If you do have more than one form on a page, users will be able to send the data from only one form at a time to the server. Every < form > element should carry at least two attributes: (1) Action (2) Method The Action Attribute The action attribute indicates what happens to the data when the form is submitted. Usually, the value of the action attribute is a page or program on a web server that will receive the information. For example, if you had a login form consisting of a username and password, the details the user enters may get passed to a page written in ASP.NET on the web server called login.aspx , in which case the action attribute could read as follows: < form action=”http://www.example.org/membership/login.aspx” >
The onsubmit Attribute The method Attribute Form data can be sent to the server in two ways, each corresponding to an HTTP method : The get method, which sends data as part of the URL. The post method, which hides data in something known as the HTTP headers. The id Attribute The id attribute allows you to uniquely identify the < form > element within a page, just as you can use it to uniquely identify any element on a page. It is good practice to give every < form > element an id attribute, because many forms make use of style sheets and scripts, which may require the use of the id attribute to identify the form. The value of the id attribute should be unique within the document. Example, frmLogin or frmSearch . The onsubmit Attribute The onsubmit attribute runs a script in the browser that checks the data you enter before the form is sent to the server. When a user clicks a submit button, something called an event fires. The idea behind these events is that a script (usually written in JavaScript) can be run before the data is sent to the server to check that users have filled in the necessary parts of the form in a format the server expects. The value of the onsubmit attribute should be a script function that would be used when this event fires. So, an onsubmit attribute on the < form > element might look like this: onsubmit=”validateFormDetails();” The onsubmit attribute tells the browser that when the user presses the submit button, the browser should run the script called validateFormDetails() , and that this script is probably in the < head > element.
Single - Line Text Input Controls Single - line text input controls are created using an < input > element whose type attribute has a value of text . Here is a basic example of a single - line text input used for a search box. < form action=”http://www.example.com/search.aspx” method=”get” name=”frmSearch” > Search: < input type=”text” name=”txtSearch” value=”Search for” size=”20” maxlength=”64” / > < input type=”submit” value=”Submit” / > < /form > Multiple - Line Text Input Controls If you want to allow a visitor to your site to enter more than one line of text, you should create a multiple - line text input control using the < textarea > element. Here is an example of a multiple - line text input used to collect feedback from visitors to a site. < form action=”http://www.example.org/feedback.aspx” method=”post” > Please tell us what you think of the site and then click submit: < br / > < textarea name=”txtFeedback” rows=”20” cols=”50” > Enter your feedback here. < /textarea > < br / >
Password Input Controls If you want to collect sensitive data such as passwords and credit card information, you can use the password input. The password input masks the characters the user types on the screen by replacing them with either a dot or asterisk, so that they would not be visible to someone looking over the user ’ s shoulder. Password input controls are created almost identically to the single - line text input controls, except that the type attribute on the < input > element is given a value of password . Here you can see an example of a login form that combines a single - line text input control and a password input control. < form action=”http://www.example.com/login.aspx” method=”post” > Username: < input type=”text” name=”txtUsername” value=”” size=”20” maxlength=”20”/> < br / > Password: < input type=”password” name=”pwdPassword” value=”” size=”20” maxlength=”20” / > < input type=”submit” value=”Submit” / > < /form >
Buttons Creating Buttons Using the < input > Element Buttons are most commonly used to submit a form, although they are sometimes used to clear or reset a form and even to trigger client - side scripts. (For example, on a basic loan calculator form within the page, a button might be used to trigger the script that calculates repayments without sending the data to the server.) You can create a button in three ways: Using an < input > element with a type attribute whose value is submit , reset , or button Using an < input > element with a type attribute whose value is image Using a < button > element Creating Buttons Using the < input > Element When you use the < input > element to create a button, the type of button you create is specified using the type attribute. The type attribute can take the following values to create a button: submit, which creates a button that submits a form when pressed. reset, which creates a button that automatically resets form controls to their initial values as they were when the page loaded. button, which creates a button that is used to trigger a client - side script when the user clicks that button. Here you can see examples of all three types of button . < input type=”submit” name=”btnVoteRed” value=”Vote for reds”/> < input type=”submit” name=”btnVoteBlue” value=”Vote for blues”/> < input type=”reset” value=”Clear form” / > < br / > < br / > < input type=”button” value=”calculate” onclick=”calculate()”/>
Using Images for Buttons You can use an image for a button rather than using the standard button that a browser renders for you. Creating an image button is very similar to creating any other button, but the type attribute has a value of image : < input type=”image” src=”submit.jpg” alt=”Submit” name=”btnImage” / > Creating Buttons Using the < button > Element The < button > element is a more recent introduction that allows you to specify what appears on a button between an opening < button > tag and a closing < /button > tag. So you can include textual markup or image elements between these tags. Here are some examples of using the < button > element: < button type=”submit” > Submit < /button > < br / > < br / > < button type=”reset” ><b> Clear this form ,</b> I want to start again < /button > < button type=”button” > < img src=”submit.gif” alt=”submit” / > < /button >
Checkboxes Checkboxes are just like the little boxes on paper forms in which you can place a cross or tick. As with light switches, they can be either on or off. When they are checked they are on — the user can simply toggle between on and off positions by clicking the checkbox. Checkboxes can appear individually, with each having its own name, or they can appear as a group of checkboxes that share a control name and allow users to select several values for the same property. A checkbox is created using the < input > element whose type attribute has a value of checkbox . Following is an example of some checkboxes that use the same control name : < form action=”http://www.example.com/cv.aspx” method=”get” name=”frmCV” > Which of the following skills do you possess? Select all that apply. < input type=”checkbox” name=”chkSkills” value=”xhtml” / > XHTML < br / > < input type=”checkbox” name=”chkSkills” value=”CSS” / > CSS < br / > < input type=”checkbox” name=”chkSkills” value=”JavaScript” / > JavaScript < br / > < input type=”checkbox” name=”chkSkills” value=”aspnet” / > ASP.Net < br / > < input type=”checkbox” name=”chkSkills” value=”php” / > PHP < /form >
Radio Buttons Radio buttons are similar to checkboxes in that they can be either on or off, but there are two key differences: When you have a group of radio buttons that share the same name, only one of them can be selected. Once one radio button has been selected, if the user clicks another option, the new option is selected and the old one deselected. Therefore, a group of radio buttons are ideal if you want to provide users with a number of options from which they must pick only one. The < input > element is again called upon to create radio buttons, and this time the type attribute should be given a value of radio . For example, here radio buttons are used to allow users to select which class of travel they want to take: < form action=”http://www.example.com/flights.aspx” name=”frmFlightBooking” method=”get” > Please select which class of travel you wish to fly: < br / > < input type=”radio” name=”radClass” value=”First” / > First class < br / > < input type=”radio” name=”radClass” value=”Business” / > Business class < br / > < input type=”radio” name=”radClass” value=”Economy” / > Economy class < br / > < /form >
Select Boxes A drop - down select box allows users to select one item from a drop - down menu. Drop - down select boxes can take up far less space than a group of radio buttons. Drop - down select boxes can also provide an alternative to single - line text input controls where you want to limit the options that a user can enter. For example, imagine that you were asking which country someone was from. If you had a textbox, visitors from the United States could enter different options such as U.S.A., U.S., United States, America, or North America , whereas with a select box you could control the options they could enter. A drop - down select box is contained by a < select > element, while each individual option within that list is contained within an < option > element. For example, the following form creates a drop – down select box for the user to select a color : < select name=”selColor” > < option selected=”selected” value=”” > Select color < /option > < option value=”red” > Red < /option > < option value=”green” > Green < /option > < option value=”blue” > Blue < /option > < /select >
File Select Boxes If you want to allow a user to upload a file to your web site from his or her computer, you will need to use a file upload box , also known as a file select box . This is created using the < input > element (again), but this time you give the type attribute a value of file: < form action=”http://www.example.com/imageUpload.aspx” method=”post” name=”fromImageUpload” enctype=”multipart/form-data” > < input type=”file” name=”fileUpload” accept=”image/*” / > < br / > < br / > < input type=”submit” value=”Submit” / > < /form > When you are using a file upload box, the method attribute of the < form > element must be post. The enctype attribute has been added to the < form > element with a value of multipart/ form - data so that each form control is sent separately to the server. This is required on a form that uses a file upload box. The accept attribute has been added to the < input > element to indicate the MIME types of the files that can be selected for upload. In this example, the accept attribute is indicating that any image format can be uploaded, as the wildcard character (the asterisk) has been used after the image/ portion of the MIME type.
Creating Labels for Controls and the < label > Element If you are creating a form for your site, it is worth spending time to provide good labeling so that the user knows what data he or she should be entering where. Some form controls, such as buttons, already have labels. For the majority of form controls, however, you will have to provide the label yourself. < form action=”http://www.example.org/login.aspx” method=”post” name=”frmLogin” > < table > < tr > < td > < label for=”Uname” > User name < /label > < /td > < td > < input type=”text” id=”Uname” name=”txtUserName” / > < /td > < /tr > < tr > < td > < label for=”Pwd” > Password < /label > < /td > < td > < input type=”password” id=”Pwd” name=”pwdPassword” / > < /td > < /tr > < /table > < /form > As you can see here, the < label > element carries an attribute called for , which indicates the form control associated with the label. The value of the for attribute should be the same as the value of the id attribute on the corresponding form control. For example, the textbox form control, where a user enters his or her username, has an id attribute whose value is Uname , and the label for this textbox has a for attribute whose value is also Uname .
Structuring Your Forms with < fieldset > and < legend > Elements Large forms can be confusing for users, so it ’ s good practice to group together related form controls. The < fieldset > and < legend > elements do exactly this — help you group controls. The < fieldset > element creates a border around the group of form controls to show that they are related. The < legend > element allows you to specify a caption for the < fieldset > element, which acts as a title for the group of form controls. When used, the < legend > element should always be the first child of the < fieldset > element.
Let ’ s take a look at the code for this example <fieldset> and <legend> < form action=”http://www.example.org/competition.aspx” method=”post” name=”frmComp” > < fieldset > < legend > < em > Contact Information < /em > < /legend > < label > First name: < input type=”text” name=”txtFName” size=”20” / > < /label > < br / > < label > Last name: < input type=”text” name=”txtLName” size=”20” / > < /label > < br / > < label > E-mail: < input type=”text” name=”txtEmail” size=”20” / > < /label > < br / > < /fieldset > < fieldset > < legend > < em > Competition Question < /em > < /legend > How tall is the Eiffel Tower in Paris, France? < br / > < label > < input type=”radio” name=”radAnswer” value=”584” / > 584ft < /label > < br / > < label > < input type=”radio” name=”radAnswer” value=”784” / > 784ft < /label > < br / > < label > < input type=”radio” name=”radAnswer” value=”984” / > 984ft < /label > < br / > < label > < input type=”radio” name=”radAnswer” value=”1184” / > 1184ft < /label > < br / > < fieldset > < legend > < em > Tiebreaker Question < /em > < /legend > < label > In 25 words or less, say why you would like to win $10,000: < textarea name=”txtTiebreaker” rows=”10” cols=”40” > < /textarea > < /label > < fieldset > < legend > < em > Enter competition < /em > < /legend > < input type=”submit” value=”Enter Competition” / > < /form >
Sending Form Data to the Server When your browser requests a web page and when the server sends a page back to the browser, you use the Hypertext Transfer Protocol (HTTP). There are two methods that a browser can use to send form data to the server — HTTP get and HTTP post — and you specify which should be used by adding the method attribute on the < form > element. If the < form > element does not carry a method attribute, then by default the get method will be used. If you are using a file upload form control, you must choose the post method. Let ’ s take a closer look at each of these methods. HT TP get: When you send form data to the server using the HTTP get method, the form data is appended to the URL that is specified in the action attribute of the < form > element. The form data is separated from the URL using a question mark. Following the question mark, you get the name/value pairs for each form control. Each name/value pair is separated by an ampersand ( & ). For example., < form action=”http://www.example.com/login.aspx” method=”get” > Username: < input type=”text” name=”txtUsername” value=”” size=”20” maxlength=”20” > < br/> Password: < input type=”password” name=”pwdPassword” value=”” size=”20” maxlength=”20” > < input type=”submit” / > < /form >
When you click the submit button, your username and password are appended to the URL http:// www.example.com/login.aspx in what is known as the query string . It should look like this: http://www.example.com/login.aspx?txtUsername=Bob&pwdPassword=LetMeIn. Note that when a browser requests a URL with any spaces or unsafe characters such as /, \ , =, & , and +, they are replaced with a hex code to represent that character. This is done automatically by the browser, and is known as URL encoding. When the data reaches the server, the server will usually un - encode the special characters automatically. One of the advantages of passing form data in a URL is that it can be bookmarked. If you look at searches performed on major search engines such as Google, they tend to use the get method so that the page can be bookmarked. The get method, however, has some disadvantages. Indeed, when sending sensitive data such as the password shown here, or credit card details, you should not use the get method because the sensitive data becomes part of the URL and is in full view to everyone. HT TP post: When you send data from a form to the server using the HTTP post method, the form data is sent transparently in what is known as the HTTP headers. While you do not see these headers, they are not, strictly speaking, secure on their own. If you are sending sensitive information such as credit card details, the data should be sent under a Secure Sockets Layer, or SSL, and they should be in encrypted.
If the login form is sent using the post method, it could be represented like this in the HTTP headers: User-agent: MSIE 7 Content-Type: application/x-www-form-urlencoded Content-length: 35 ...other headers go here... txtUserName=Bob & pwdPassword=LetMeIn Note that the last line is the form data, and that it is in exactly the same format as the data after the question mark in the get method — it would also be URL - encoded so any spaces or unsafe characters such as /, \ , =, & , and + (which have special meanings in URLs) are replaced with a hex code to represent that character as they were in HTTP get requests. < form action=”http://www.example.com/newsletter.asp?action=subscribe” method=”post” > The only issue with using the HTTP post method is that the information the user entered on the form cannot be bookmarked in the same way it can when it is contained in the URL. So you cannot use it to retrieve a page that was generated using specific form data as you can when you bookmark a page generated by most search engines, but it is good for security reasons.