Introduction to Forms
Forms provide an interface for collecting, displaying, and delivering information, and are a key component of HTML. By providing different controls such as text fields, buttons, and checkboxes, forms can enhance Web pages with a means to exchange information between a client and a server. The various controls allow authors and users to perform actions, make choices, and quickly identify and enter information. When the form data is submitted to the server- or client-side script, the information either is parsed and cataloged, or redirected in response to the submission. Forms are prevalent throughout all graphics-based operating systems and Web pages.
Web-based forms are supported in most browsers, and including forms in a Web page is relatively straightforward. This overview introduces form controls, discusses form design and accessibility, and provides a first step to submitting and managing form data.
- Advantages of Forms
- Form Controls
- Implementing Forms
- Organizing and Enhancing Forms
- Working with Text
- Submitting Forms
- Submission Issues
- Related Topics
Advantages of Forms
Using forms is advantageous because they are:
- Easy to implement. There are several controls that provide a means to exchange information with a user.
- Extensible. Dynamic HTML (DHTML) allows an author to update and modify forms and controls as needed.
- Accessible. Using the Cascading Style Sheets (CSS) attributes, supported as of Microsoft Internet Explorer 4.0 and later, allows authors to tailor form controls with specific styles.
Forms provide a convenient interface for exchanging information between a server and a client, and allow an author to quickly create and distribute an HTML interface to a large audience. With DHTML, Web authors can enhance forms using CSS and client-side scripting languages, such as Microsoft JScript and Microsoft Visual Basic Scripting Edition (VBScript).
To enhance a form's visibility and make its controls easier to use, an author can apply CSS attributes, such as positioning and dynamic styles. Combined with robust client-side scripts, forms also can be enhanced to provide validation or masking, or even to perform calculations once reserved for the server.
Form Controls
Form controls allow authors to provide Web sites with benefits similar to other graphics-based programming languages. The following table provides a list of the supported form controls, when they were first available in Internet Explorer, what attributes are submitted, and a description.
Element/Control | Availability | Submitted | Description |
---|---|---|---|
button | 4.0 | NAME, VALUE | Rich button control that can include DHTML is rendered. When submitted, Internet Explorer 4.0 submits the innerText property, and Internet Explorer 5 and later submits the NAME/VALUE pair. |
input type=button | 3.0 | NAME, VALUE | input element is rendered as a button. Events such as onclick can be included with the button to provide action when it is clicked. |
input type=checkbox | 3.0 | NAME, VALUE | input element is rendered as a check box. The check box is useful for selecting multiple groups of topics (for example, selecting favorite magazines) and Boolean decisions (for example, adding your e-mail to the mailing list). Events such as onclick can be used in conjunction with the checked property to determine conditions (for example, displaying a hidden object). |
input type=file | 4.0 | NAME, VALUE (encoded) | Nonscriptable text field and Browse button are rendered. The ENCTYPE attribute for a form must be set to multipart/form.data for this control to work properly. For security reasons, the VALUE attribute is not accessible in script on the client. |
input type=hidden | 3.0 | NAME, VALUE | Hidden control is rendered, and is useful for submitting additional information that does not need to be displayed to the user. |
input type=image | 3.0 | NAME | Submit control is rendered as an image. The image control is a useful alternative to using buttons. When the image control is clicked, it is the only image control submitted for the form. In addition, an image control is submitted only if the NAME attribute is specified. |
input type=password | 3.0 | NAME, VALUE | Text field masked with asterisks is rendered. The password field is useful on the client for shielding private information from anyone looking at the same screen. |
input type=radio | 3.0 | NAME, VALUE | Radio control is rendered, and is useful for selecting one item from a set. Selecting one radio control clears any other radio controls with the same NAME attribute value. |
input type=reset | 3.0 | Button that resets all form values is rendered. | |
input type=submit | 3.0 | NAME, VALUE | Button that sends all the information for a particular form to the script or program specified in the ACTION attribute is rendered. The METHOD attribute specifies the way in which the form information is delivered. Submit controls are sent only if the NAME attribute is defined. If more than one submit control exists in a particular form, only the control that is clicked is sent. |
input type=text | 3.0 | NAME, VALUE | Single-line text field is rendered. |
select | 3.0 | NAME, option(selected) | Drop-down list box or list box is created, comprised of included option elements, or created dynamically using the options collection and add method. A list box is created by specifying a value greater than 1 for the SIZE attribute. Multiple options in a list box can be selected by including the MULTIPLE attribute. If the MULTIPLE attribute is included, a list box is created. If the SIZE and MULTIPLE attributes are not present, a drop-down list box is created. |
textArea | 3.0 | NAME, VALUE | Text field with multiple lines is rendered. The VALUE attribute of the textArea element is equivalent to the innerText property, and is located between the opening and closing tags. |
Implementing Forms
Before implementing forms on a Web site, the need for the form element must be determined. The form element is necessary for submitting form controls to a server. When a form is submitted, only the name/value pairs for the controls within the submitted form element are sent. The form element is not necessary if form controls are being used only for client-side scripting. However, other browsers may require the element before the controls are rendered.
When using the form element, the ACTION and METHOD attributes specify how and where the data in the form controls is delivered. The two methods used are get and post.
- The get possible value specifies that the form data is appended to the URL specified in the ACTION attribute, and limits the amount of data to 256 characters. This method is deprecated due to the size limitation and visibility in the document location. However, it is useful for debugging transactions, because the submission string is visible as a part of the path.
- The post possible value sends form data as a post transaction, is not limited in size, and is the preferred method for delivering data to the server.
A form action is any script designed to process the delivered information and reply to the HTTP server, so that results can be returned to the client. The following sample demonstrates the syntax of the form element that sends form data as a post transaction to an ASP.
<FORM ACTION = "process.asp" METHOD = "post"> : </FORM>
Form controls are added to Web pages as HTML elements. For example, adding two text fields for the first and last names of visitors only requires the input type=text control.
<FORM> First Name: <INPUT TYPE = "text" NAME = "FirstName"> <BR> Last Name: <INPUT TYPE = "text" NAME = "LastName"> </FORM>
When adding controls, it is important to understand the difference between the ID and NAME attributes. Both attributes are accessible through client-side scripting, but only the NAME is passed when the form is submitted. In addition, the ID can be referred to directly in script while the NAME must be referred to by including the NAME of the parent form, if the element is a child of a form element. For example, if a Web author wants to access the VALUE attributes of the FirstName text field on the client, the following considerations must be taken into account.
<FORM NAME = "Form1"> <INPUT TYPE = "text" ID = "oFirstName" NAME = "FirstName" > </FORM>
- If the ID attribute is assigned, the element can be directly accessed within script. Keep in mind that the ID is not submitted.
var sFirstName = oFirstName.value;
- If the text field is not a child of a form element, the NAME attribute can be used to identify the text field.
var sFirstName = oFirstName.value;
- If the text field is a child of a form element and does not have an assigned ID attribute, then the NAME attribute of the form, or the ordinal position of the form in the forms collection, must be used to access the text field. In addition, the item method can be used to refer to a particular control of the form without specifying the NAME or ID.
// Access the VALUE through the form NAME var sFirstName = Form1.FirstName.value; // Access the VALUE through the forms collection using the NAME attribute. var sFirstName = document.forms[0].FirstName.value; // Access the VALUE through the forms collection using the item method. var sFirstName = document.forms[0].items[0].value;
The input type=text, input type=password, and textArea controls are useful for submitting name/value pairs. A Web author may want more specific information or a more controlled environment for entering information. Ensuring that the correct information is supplied is critical for databases that rely on specific values for queries. It is useful to provide preset values and choices that can be selected when particular information is required.
The select, input type=checkbox, and input type=radio controls are ideal for selecting preset information and making choices without requiring (though allowing) keyboard input. This makes it easier and faster for users to supply information, and it means that the Web author or system administrator knows the exact value combinations.
The select control is extremely useful for quickly selecting one or more items from a predefined or dynamically constructed list. Implementing the select control is straightforward, but doing something with the control can be difficult. The select control allows a Web author to choose from several implementations using the SIZE and MULTIPLE attributes.
The three primary implementations of the select control are illustrated in the following diagram, accompanied by the attribute settings used to achieve the rendered version.
The three different implementations of the select control are a drop-down list box, a list box, and a multi-select list box. The option object is used to populate the control. Referring to the selected values requires being able to identify the control and the selected option. To retrieve the selected value, the selectedIndex property is used with the options collection to identify the particular item. For example, the following code contains a sample select control and a few lines of script that use the alert method to display the selected value when the onchange event fires.
<SCRIPT> function fnShowText(){ /* Use the selectedIndex property of the SELECT control to retrieve the text from the options collection. */ var sText = oSel.options(oSel.selectedIndex).text; alert(sText); } </SCRIPT> <SELECT ID = "oSel" onchange = "fnShowText()"> <OPTION>Luna <OPTION>Saturn <OPTION>Europa <OPTION>Io <OPTION>Jupiter <OPTION>Monolith </SELECT>
A somewhat different approach is required to retrieve the selected values from a multi-select list. By iterating through all the options, the selected property can be queried to determine if the option is selected. If so, the current index of the iteration can be used to acquire the text or value of the item. The following sample code demonstrates how this is done.
<SCRIPT> function fnShowText(){ /* Look through all the options to find selected items. */ for(var i = 0; i < oSel.options.length; i++){ /* Check to see if a particular option is selected */ if(oSel.options(i).selected){ /* Return the selected value */ alert(oSel.options(i).text); } } } </SCRIPT> <SELECT ID = "oSel" MULTIPLE SIZE = "5" onchange = "fnShowText()"> <OPTION>Luna <OPTION>Saturn <OPTION>Europa <OPTION>Io <OPTION>Jupiter <OPTION>Monolith </SELECT>
When a multi-select list is submitted, the items are sent as a comma-delimited list. If a VALUE attribute is not provided as an option, the TEXT attribute is sent instead.
The input type=checkbox and input type=radio controls provide similar interfaces with different capabilities. When the NAME attributes for two or more input type=radio controls are the same, the controls act as a collection. As a collection, only one input type=radio control can be checked at a time. Selecting one option at a time makes this control ideal for Boolean choices, or options that only have one possible value.
For example, if an elementary school history teacher wants to design a multiple-choice exam, the choices could be comprised of radio controls. The following sample demonstrates how the input type=radio control is implemented. To provide label elements, each radio control receives a unique ID attribute, while the NAME attribute remains the same to allow the controls to function as a collection. An input type=button object is included to provide the correct answer, and an onclick event is used to verify the checked property of the controls.
<FORM NAME = "Form1"> The first President of the United States was: <TABLE> <tr> <td> <LABEL FOR = "oRadio1">George Washington</LABEL></td> <td><INPUT TYPE = "radio" NAME = "radio1" ID = "oRadio1"></td> </tr> <!-- Place additional choices here --> </TABLE> <INPUT TYPE = "button" VALUE = "Check Answer" onclick = "fnGetAnswer()"> </FORM>
To determine which radio control is selected, the collection is accessed and the checked property is verified.
<SCRIPT> var aRadio1Answers=new Array("Correct.","Incorrect","Incorrect,"Incorrect"); function fnGetAnswer(){ for(var i=0;i<Form1.radio1.length;i++){ if(Form1.radio1(i).checked){ alert(aRadio1Answers[i]); } } } </SCRIPT>
On the other hand, if several choices from a group need to be made, then the input type=checkbox control can be used. For example, if a teacher wants to test a student's knowledge about a range of information, the input type=checkbox control is preferred for allowing a series of choices to be made. The syntax is the same as the radio control, only the TYPE attribute is different.
Select the inventions created before 1500 AD. <FORM NAME="Form1"> <TABLE> <TR> <TD><LABEL FOR = "oInvention1">Crop Rotation (science)</LABEL></TD> <TD><INPUT TYPE= "checkbox" NAME = "invention1" ID = "oInvention1"></td> <!-- Place additional choices here --> </TABLE> <INPUT TYPE = "button" VALUE = "Check Answers" onclick = "fnCheck()"> </FORM>
In this example, the correct values are predetermined. In fact, checking for the correct values is easy. However, it gets a little tricky checking for incorrect values and handling the different cases.
// Preset binary markers for the correct answers. var aAnswers=new Array(0,1,0,0,0,1,1,0,1,1); // Total number of correct answers possible. var iTotalCorrect=5; // Number of attempts to submit answers. var iTries=0; function fnCheck(){ // Increment tries and set correct and incorrect answers to zero. iTries++; var iCorrect=0; var iIncorrect=0; // Use an array of preset binaries and see if the correct control is checked. for(var i=0;i<Form1.invention1.length;i++){ // If the check box is checked and the binary is 1, it is a // correct answer. if((Form1.invention1(i).checked)&&(aAnswers[i]==1)){ iCorrect++; } // If the check box is checked and the binary is 0, it is an incorrect answer. if((Form1.invention1(i).checked)&&(aAnswers[i]==0)){ iIncorrect++; } } // If there are fewer correct answers than the total, or there // are any incorrect answers, return the following message. if((iCorrect<iTotalCorrect)||(iIncorrect>0)){ alert("You have some correct and " + iIncorrect + " incorrect answers."); } // If there are no incorrect answers, and all the correct answers // are chosen, continue. if((iCorrect==iTotalCorrect)&&(iIncorrect==0)){ // Proceed based on number of attempts. if(iTries==1){ alert("Congratulations, you got them all right on the first try!"); } else{ alert("Congratulations. It took " + iTries + " tries."); } } }
Organizing and Enhancing Forms
Forms can quickly become large and difficult to organize and use. Internet Explorer 4.0 and later supports several features that help authors manage forms, and help users quickly jump to particular places on a form.
- Visual enhancements provide authors with an effective way to organize how forms are positioned on a document.
- Keyboard enhancements provide users with a quick, logical way of accessing specific areas of a form.
The following image shows how the fieldSet and legend elements can be used to group input type=text and label elements together.
Using the enhancements just mentioned, a form can be organized to make it available to more users. The following code demonstrates how these enhancements are implemented.
<!-- The FIELDSET is a container for the controls. --> <FORM> <FIELDSET STYLE="width: 200;"> <!-- The LEGEND identifies the FIELDSET --> <LEGEND>Accessibility Form</LEGEND> <TABLE> <TR> <TD> <!-- A TABINDEX of -1 specifies this object is skipped. --> <LABEL TABINDEX = "-1" FOR= "oFirstName"> <!-- The acceleration key is underlined for easy identification --> <SPAN STYLE = "text-decoration: underline;">F</SPAN>irst Name </LABEL> </TD> <TD> <!-- The ID is defined for the LABEL, the NAME is provided for form submission --> <INPUT TABINDEX = "1" TYPE = "text" ID = "oFirstName" NAME = "FirstName" ACCESSKEY = "F"> </TD> </TR> </TABLE> </FIELDSET> </FORM>
The AutoComplete feature, available in Internet Explorer 5 and later, provides further enhancements to forms usability. For more information, see the Using AutoComplete in HTML Forms overview.
Working with Text
Text plays an important role in forms, particularly for messages, database queries, or updating content. In addition, managing text is a prerequisite for developing any sort of word processing or data organization, such as with spreadsheets. Since form controls primarily are designed to work with ASCII text, formatting the value within the control can be extremely difficult.
The form controls that permit direct user input are the input type=text and textArea elements. The textArea element is ideal for entering messages with multiple lines. The size of the textArea element is adjustable using the COLS and ROWS attributes. Wordwrap is specified using the WRAP attribute. The following sample code highlights the syntax for a textArea element using the COLS, ROWS, and WRAP attributes.
<TEXTAREA COLS = "50" ROWS = "10" WRAP = "hard"> ... </TEXTAREA>
Beyond simply entering text messages, the textArea element is useful for working with raw information provided by the user. For example, if a technical-support Web site wants to provide an automated feature that checks for temporary files that can be deleted, then a total list of files from a particular directory may be required from the user. An easy and security-conscious way to get this information from the user's hard drive to the Web site would be to simply have the user paste the file list into a textArea element. Once the file list is provided, the Web site can then proceed to analyze the files in client-side script.
A common character is all that is needed to convert the VALUE attribute of the textArea element into a functional list for analysis. In this case, a line return can be used to parse the VALUE and create an array. The following code demonstrates how this is done.
<SCRIPT> function fnParseValue(){ var oFileArray = new Array(); oFileArray = oConvert.value.split("\n"); // This returns a script array that can now be sorted or altered. } </SCRIPT> <TEXTAREA onpaste = "fnParseValue()" ID = "oConvert"> Past file list here. </TEXTAREA>
Submitting Forms
When a form element is submitted, only the controls within that element are sent. There are many different reasons to use forms, but there are only a few locations to which the information can be sent. Form submissions can be sent to:
- Client-side script, a Java applet, or an Microsoft ActiveX control.
- Server-side script, a servlet, or a control.
- E-mail.
Form information can be processed on the client using JScript, VBScript, or any other supported scripting language. Processing form information on the client is useful for any Web-based utility or tool not requiring interaction with the server. If the form data needs to be written to a file or added to a database, then server interaction most likely is required.
The script or application handling the form submission is specified by the ACTION attribute. This script can be just about any script or application that is supported by the Web server or operating system, and that generates results the client can understand (typically HTML). The scripts that handle form submissions are referred to as Common Gateway Interface (CGI) scripts. Some languages that CGI scripts are written in are Perl, Visual Basic, Microsoft Visual C++, and Java.
Web authors also can use server-side script embedded in the Web document, such as ASP. Server-side script is preprocessed by the Web server, and the results are generated in HTML. For example, ASP allows Web authors to use predefined scripting objects and implementations of client-side script to achieve the same results as other CGI-capable languages.
Whether it is designed to be processed on the client or on the server, a form can be submitted in one of the following ways:
- Using the input type=submit control.
- Using the input type=image control.
- Using the button object with the TYPE attribute set to submit.
- Using the submit method in script.
In addition to using a scripting language, a control, or an application, forms also can be submitted using the mailto protocol. It is recommended to set the METHOD attribute to post and the ENCTYPE attribute to text/plain on the form element when using mailto. To use this protocol, the e-mail message can be constructed within the mailto protocol, or using the e-mail form names. If no names are provided, the information simply is appended to the e-mail body. The following list provides e-mail form names and a description of each one.
- Recipient specifies the primary address to where the e-mail is sent.
- Subject specifies the subject of the e-mail document.
- CC specifies the recipient of a carbon copy of the e-mail.
- BCC specifies the recipient of a blind carbon copy of the e-mail. The carbon copy and primary recipients do not see addresses included in the BCC field.
- Body specifies the body of the e-mail document.
Using these particular field names only is practical when the mail path is not constructed in script. The following sample outlines an e-mail form that constructs the form action when the onsubmit event fires.
- The e-mail form is a basic form with four text fields, one textArea element, a Submit button, and a Reset button. The button object is used instead of the input type=submit and input type=reset controls, so that the value can reflect the ACCESSKEY accessibility.
<FORM METHOD = "get" onsubmit = "fnSetAction()" NAME = "oMailForm"> <LABEL FOR = "oTo"><SPAN>A</SPAN>ddress:</LABEL> <INPUT ACCESSKEY = "A" ID = "oTo" VALUE = "" TYPE = "text" NAME = "recipient"> <BR> <LABEL FOR = "oSubject"> <SPAN>S</SPAN>ubject:</LABEL> <INPUT ACCESSKEY = "S" VALUE = "" ID = "oSubject" TYPE=text name="subject"> <BR> <!-- Repeat for additional fields --> <LABEL FOR=oBody><SPAN>M</SPAN>essage Body:</label> <TEXTAREA TYPE=text ACCESSKEY="M" COLS=40 ROWS=5 ID=oBody TYPE=text NAME="body"> </TEXTAREA> <BR> <BUTTON ACCESSKEY="E" TYPE=submit> Send <SPAN>E</SPAN>mail </BUTTON> <BR> <BUTTON ACCESSKEY="R" TYPE=reset> <SPAN>R</SPAN>eset E-mail Form </BUTTON> </FORM>
- The onsubmit handler demonstrates how the e-mail message is added to the mailto protocol. The mailto protocol is created from a string of values based on the form fields and appended to the ACTION attribute. This is not necessary if the form field names match the e-mail field names.
<SCRIPT> function fnSetAction(){ if(oMailForm.recipient.value!=""){ var sAction="mailto:" + oMailForm.recipient.value; if(oMailForm.subject.value!=""){ sAction+=""&Subject=" + oMailForm.subject.value; } if(oMailForm.cc.value!=""){ sAction+="&cc=" + oMailForm.cc.value; } if(oMailForm.bcc.value!=""){ sAction+="&bcc=" + oMailForm.bcc.value; } if(oMailForm.body.value!=""){ sAction+="&body=" + oMailForm.body.value; } oMailForm.action=sAction; } else{ alert("Address required."); } } </SCRIPT>
When the form is submitted to the CGI script specified by the ACTION attribute, the location of the form data is specified by the METHOD attribute. If the possible value get (deprecated) is used, the form data is appended to the URL, and a 4K limit is imposed. However, if the possible value post is used, the form data is sent with the HTTP header without a size limit.
The get possible value is advantageous for debugging scripts or learning how the submission process works. When using the get possible value, the form data can be retrieved in client-side or server-side script by analyzing the href property on the location object. The following sample demonstrates how this information is accessed through script. Consider a form with controls named oFirstName, oLastName, and oPhrase.
var aData=new Array(); function fnInit(){ var sLocation= location.href; var sData = sLocation.substring(sLocation.indexOf("?") + 1,sLocation.length); aData = sData.split("&"); for(var i = 0;i < aData.length;i++){ var sName = aData[i].substring(0,aData[i].indexOf("=")); var sValue = aData[i].substring(aData[i].indexOf("=")+1,aData[i].length); alert(sName + ' = "' + unescape(sValue)); } }
After a form is submitted, the form data is appended to the URL. For instance, after the file name extension of the CGI script specified by the ACTION attribute, the form data might have the following appearance:
?oFirstName=Gertrude&oLastName=Spencer&oPhrase=My%20favorite%20color%20is%20plaid.
The first character in the preceding form data is a question mark (?), and it specifies that information following it is form data. Each name/value pair is grouped with the form control name, an equal sign (=), and the value. The value is encoded so that spaces and special characters are converted to their ASCII equivalents. Each name/value pair is separated by an ampersand (&).
The steps to recover the form data from the URL are as follows:
- Separate the name/value pairs from each other.
- Split the name from the value.
- Unencode the value.
After the values are unencoded, a Web author can continue using the form data through script.
When a form is submitted using the post possible value, and the form data is appended to the HTTP header, the CGI script specified in the ACTION attribute generally provides a means to recover the name/value pairs. Keep in mind that the submitted form information is available through client-side script when using the possible value get, but not when using post.
Submission Issues
Submitting forms sometimes requires some insight into data management and the ability to adapt to new technology. As the document object model in Internet Explorer grows, and objects are interwoven with one another, it is not always clear as to how information can be sent to the server from objects that are not submitted with a form. One of the best solutions is to use an existing form control.
For example, a new technological feature, available as of Internet Explorer 5, is DHTML technological behaviors. While behaviors provide a robust information-access solution to Web authors, they are not inherently submitted with the form element unless they are part of a form control. It is unnecessary, though, for a behavior to be submitted with other controls simply because the methodology exists to handle this case. Information supplied by the behavior can be easily transferred to the VALUE attribute of an input type=hidden control, or any other control that submits the VALUE attribute. If a Web author wants to send information gathered from the clientCaps behavior, that information can be moved to a form control for the submission process.
The following code outlines how information gathered from a DHTML behavior can be submitted using a form control.
Start with a textArea control, an object participating in the CLIENTCAPS behavior, and a button to copy the data.
<TEXTAREA ID = "oOutput" COLS = "50" ROWS = "10"> </TEXTAREA> <DIV ID = "oClientCaps" STYLE = "url(#default#clientCaps)"> </DIV> <INPUT TYPE = "button" VALUE = "Copy Data" onclick = "fnGetCaps()">
Next, prepare the information in a format that can be accessed and used on the server, or can be the target of the form submission. For this sample, the information is stored in a comma-delimited list.
<SCRIPT> function fnGetCaps(){ try{ oClientCaps.style.behavior = "url(#default#clientCaps)"; var sClientData=""; for(var i=0;i<pClientCaps.length;i++){ sClientData+="|" + pClientCaps[i] + "|,|" + eval("oClientCaps." + pClientCaps[i]) + "|\n"; } oOutput.value=sClientData; } catch(e){ alert("Exception Error:\n\n" + e.error); } } </SCRIPT>
With the growing popularity of DHTML, there are times when form controls are not needed, but information needs to be submitted. The input type=hidden control is an ideal solution, because the name/value pair is submitted, but the control itself is not rendered. Web authors also can use CSS attributes and DHTML behaviors to enhance form controls, because they allow the controls to be better integrated with other designs on a particular page.
Tidak ada komentar:
Posting Komentar