CIS 4004: Web Based Information Technology Summer 2014

Transcription

CIS 4004: Web Based Information TechnologySummer 2014Inside HTML5 – Part 4 - FormsInstructor :Dr. Mark Llewellynmarkl@cs.ucf.eduHEC 236, sum2014Department of Electrical Engineering and Computer ScienceUniversity of Central FloridaCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 1 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms One of the biggest problems with XHTML and HTML 4forms was that they were just dumb fields. Validation wasrequired not only on the server-side, but also you had toduplicate the validation in the user ’ s browser usingJavaScript if you wanted to give the user the seamlessexperience they deserve. Given that almost every web page has some kind of form –search, comments, sign-up, and so on, HTML5 has come tothe rescue and provides built-in validation for many of themost common types of data entered via web forms.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 2 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms HTML5 makes developing forms quicker. There are somenice goodies like the addition of two new HTTP types forform action (update and delete) to go along with thecurrent get and post actions. The most useful new features and the new form input typeswhich provide special user interfaces and built-in errorreporting. Eventually, you won’t need JavaScript validation at all forthese fundamental data types. Until everyone is using anHTML5 browser, some JavaScript validation will still berequired.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 3 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms It was actually the new form fields that were at the basis of thespecification that ultimately became HTML5. It is also in thisarea where you’ll see the principle of specifying backwardscompatible extensions to HTML5 in action. The extensions are largely new values of the type attribute ofthe input element. XHTML and HTML4 specified that browsers should assume input type text if you don ’ t specify a typeattribute, or you use an unknown type. Therefore, legacybrowsers that don’t understand the new extensions will fallback to the default and will allow the user to enter data in aplain text field. This fallback can be detected in JavaScriptand handled so that old browsers can mimic the newbehaviors.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 4 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms The HTML5 specification makes no requirements on howbrowsers should present the new input types to the user orreport errors (handle validation). Different browsers anddifferent devices will present different user interfaces, as wewill see. The manner in which the browser reports errors is alsoundefined by the HTML5 specification. Error messages arepart of the browser and are thus automatically localized. Thismeans much less work for the developer and a more usableexperience for the consumer.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 5 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms The HTML5 specification makes no requirements on howbrowsers should present the new input types to the user orreport errors (handle validation). Different browsers anddifferent devices will present different user interfaces, as wewill see. The manner in which the browser reports errors is alsoundefined by the HTML5 specification. Error messages arepart of the browser and are thus automatically localized. Thismeans much less work for the developer and a more usableexperience for the consumer.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 6 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms There are two basic parts to any form: the collection of fields,labels, and buttons that the visitor sees on the page andhopefully fills out; and the processing script that takes thatinformation and converts it into a format that you can read ortally, or process in some manner perhaps on a database. Constructing a form’s fields and buttons is straightforwardand similar to creating any other part of the web page. Someof these form field types include text boxes, special passwordboxes, radio buttons, checkboxes, drop-down menus, largetext areas, and even clickable images. Each element has a name that will serve as a label to identifythe data once it is processed. CSS is used to style the form.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 7 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms Using forms often requires using a server-side scriptinglanguage to receive the submitted information. It requirescode on the web server that listens for form responses andprocesses the information in the response by storinginformation in a database, sending it in an email, or redirectingthe user to new information. PHP is often the server-side scripting language that is utilizedfor this purpose, but there are many other server-side scriptinglanguages. We’ll cover PHP in more depth later in thecourse. Before we look at some of the new HTML5 form elements,let’s examine creating basic forms and processing them.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 8 Dr. Mark Llewellyn

Inside HTML5 – Part 4 - Forms Every form has 3 basic parts:– The form element.– The actual form elements where the visitor enters information.– The submit button that sends the collected information to the server. The form element includes the URL of the script that willprocess the form and its method (get, post, etc.). The example on the following page is a snippet of markupfrom a much larger form that we’ll examine later. Thisexample shows only a very simple form.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 9 Dr. Mark Llewellyn

The form elementURL of the PHP script to process dataSubmit button to send data to scriptCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 10 Dr. Mark Llewellyn

Rendering of the form inSafari with no CSSappliedThe submit buttonCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 11 Dr. Mark Llewellyn

Part of the CSS to stylethe form exampleCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 12 Dr. Mark Llewellyn

Rendering of the form inSafariThe submit buttonCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 13 Dr. Mark Llewellyn

Visitor fills in the form andthe data in the form isextracted by theshowformdata.phpscript running on theserver.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 14 Dr. Mark Llewellyn

Output from theshowformdata.phpscript.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 15 Dr. Mark Llewellyn

Fieldsets and Legends Let’s look at some of the basic form elements in the previousexample and see how they can be styled and grouped to create aform that is both visually appealing as well as useful for your webpage. If you have a lot of information to fill out on a form, you can use afieldset element to group related elements and make the formeasier to follow. The easier it is for your visitors to understand theform, the more likely they are to fill it out correctly. You can also use the legend element to give each fieldset acaption that describes the purpose of each grouping. However,there is currently an almost universal lack of browser support forvisual control over the legend element, so I recommend usingregular heading elements.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 16 Dr. Mark Llewellyn

Fieldsets and Legends The legend element limits the power of CSS to position it. It is thisreason that its styling is limited in most browsers. I recommendthat you use an appropriately styled p element or h1 - h6 element to recreate its effect. Notice that this is the approach I tookin the previous example. Text boxes can contain one line of freeform text – that is, anythingthat the visitor wants to type – and they are typically used fornames, addresses, and so on. There are many ways to separate your form elements from eachother. In this example, I an using unordered lists, but it is alsocommon to see div , p or br elements used in thiscontext.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 17 Dr. Mark Llewellyn

Textboxes Personally, I feel that the unordered list is more semantically correctfor this as I would view a form as a list of elements to be completedby the visitor before they click the submit button. Text boxes can be different sizes to accommodate different types offields. In the previous example, I used a CSS style sheet to set thewidth using classes. However, you can also set the width with thesize “n” attribute on the HTML5 element itself. I wouldnormally take this approach as it is easier to make changes to a formin general via CSS than it is to go through the markup looking forsize attributes in the various form elements. While every form element must have the name attribute set, thevalue attribute is optional and only needs to be specified if theform element is to have a default value.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 18 Dr. Mark Llewellyn

Textboxes The name attribute must be specified for each element of yourform. The reason is that this is how you access these values on theserver to which the form data is sent for processing. Older versions of IE can get the name and id attributes confusedwhen the script uses the getElementByID method. The way thisis normally handled is to use the same unique value for both thename and id for each field in the form. This enhances theaccessibility of your form. Notice that this is the approach I took inthe previous example.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 19 Dr. Mark Llewellyn

HTML5 Form Attribute Enhancements Forms are one area of HTML that many developers findpainstaking, because it often requires extra effort with CSS andJavaScript to make them function well. HTML5 has made some significant improvements to forms byadding many form enhancements that were not available in HTML4 or XHTML. These enhancements include attributes autofocus, required,placeholder, maxlength, and pattern. I’ll introduce someof these as we go along with additional examples, but if you look atthe complete code for the previous example (see course webpagefor complete markup and next page for quick view), you’ll see thatboth required and placeholder were used in text box for thefirst name.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 20 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 21 Dr. Mark Llewellyn

Placeholders are a great way to give visitors ahint or extra instructions for filling out theform. The placeholder attribute will put text ina light grey color inside your text box. Whenthe user begins to input text in the file, thelight grey text will disappear, and it will comeback if the user leaves the field withoutentering any information.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 22 Dr. Mark Llewellyn

HTML5 Form Attribute Enhancements The required attribute can be applied to any number of fields ina form. Any field that is designated as required must have a valueentered in the field for the form to submit. If the user clicks thesubmit button and a required field has no data entered and error willbe generated and the form data will not be submitted to the server. When desired, an element can have the autofocus attribute set tohave a value of autofocus. If it is the first element to have thisattribute, the input element will by default have focus when thepage loads. Notice in the previous example, that no element hadautofocus set, so the visitor was required to click on the first (orsome) element to begin filling out the form. Notice the differencein the two renderings on the next page.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 23 Dr. Mark Llewellyn

No autofocus on firstelement of formCIS 4004: Web Based IT (Inside HTML5 – Part 4)Autofocus on first elementof formPage 24 Dr. Mark Llewellyn

Password Boxes The only difference between a password box and a regular text boxis that whatever is typed in the password box is hidden by bullets orasterisks. The information is not encrypted when it is sent to theserver. A password box only keeps onlookers from seeing a user’spassword as it is typed. To really protect the password, a secure(https) server connection must be utilized.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 25 Dr. Mark Llewellyn

Labeling Form Parts HTML5 provides a semantic method for marking up labels so thatthey are formally linked to the associated element. This makesthem useable for scripting and other purposes. Notice in the example markup (see page 10) that each form elementis inside a label element with a for attribute. For example, you might want to have “First Name” before the textfield where the visitor should type their first name.CAUTION ! ! !Placeholders are sometimes incorrectly used as a replacement for the label. Besure to use placeholders as hints to the visitor only.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 26 Dr. Mark Llewellyn

Labeling Form Parts Using field labels in this semantically correct way gives you an easyway to identify them in a CSS style sheet. If you use the for attribute, you must also add the id attribute tothe associated form element’s start tag in order to mark it with alabel. The document will not validate if you miss this step and usea label but do not include a matching id. Using the for attribute in the label requires that the label matchthe id attribute of the form element. Labels for radio buttons and checkboxes (more later) allow the userto click the label as well as the form element to modify the state.This is sometimes easier for the visitor to do than to place the cursoron a small dot or checkbox.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 27 Dr. Mark Llewellyn

Radio Buttons Radio buttons are used when you want to provide the visitor,typically a limited number of options for some field, but the visitoris limited to being able to select only one of the options. Radio buttons are named after the type of radios that many old carshad in which selecting a station was done by depressing a selectorbutton. Only one selector button could be pushed at a time. The name attribute serves a dual purpose for radio buttons: it linksthe radio buttons in a given set together, and it identifies the valuewhen it is sent to the script for processing. The value attribute is crucial for a radio button, since the visitorhas no way of typing a value for a radio button. Part of the large form example that illustrates radio buttons is shownon the next page.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 28 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 29 Dr. Mark Llewellyn

CSS is used to style the radio button listelements to display inline rather than vertical.Also, the radio button labels have a rightmargin of 25 pixels to separate the radiobutton label pair.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 30 Dr. Mark Llewellyn

Radio Buttons If desired, the attribute checked “checked” can be set tomake the radio button active by default when the page is opened.You can do this to only one radio button in the set. If you do not set the value attribute, the word “on” is sent to theprocessing script. Its not particularly useful, since you cannot tellwhich button in the set was selected. For radio buttons only, the name attribute must be the same forevery radio button in the set. The id attribute for each element onthe page must be unique.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 31 Dr. Mark Llewellyn

Selection Boxes Selection boxes are a convenient way to offer your visitors a choicefrom a given set of options. They are most often rendered as dropdown lists. You can give the user the option of choosing only one option orseveral options from the list. Selection boxes render as a box of items with a scroll bar. Selection boxes are made up of two HTML5 elements: select andoption. You set the common name attribute in the select elementand you set the value attribute in each of the option elements. The part of the big example markup that displays the selection boxis shown on the next page.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 32 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 33 Dr. Mark Llewellyn

Exploded view of the selection box activatedby the visitor who will be selecting the Floridaoption. When the user lets up on the click –the form element will change to mirror theirselection.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 34 Dr. Mark Llewellyn

Selection Boxes A visitor will not be able to not make a selection in a menu unlessyou set the size attribute. If you have a particularly large menu of items, you may want togroup the options into categories. Before the first option elementin the first group that you want to place together enter anoptgroup element and enclose all of the subgroup menu itemsinside the optgroup element.Repeat this for as manysubgroupings as you’d like to create. Browsers generally do not create true submenus, but rather groupthe items into a single menu with subgroups. The example on the next page illustrates this concept.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 35 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 36 Dr. Mark Llewellyn

Exploded view of the subgrouping of theselection box.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 37 Dr. Mark Llewellyn

Selection Boxes The attribute selected “selected” is used to specify that anoption in the selection box is to be selected by default. If desired, the attribute size “n”, where n represents the height(in lines) of the selection box can be used to define how many linesare visible at one time by the visitor. If you use the size attribute, the selection box appears more like alist, and there is no automatically selected option (unless you useselected). If size is bigger than the number of options, visitors can deselectall values by clicking in the empty space.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 38 Dr. Mark Llewellyn

Check Boxes Radio buttons can accept only one answer per set (grouping of radiobuttons). Check boxes allow the user to select as many options in aset as they like. Similar to radio buttons, check boxes are linked together in a set orgroup via the value of the name attribute. The visitor can select as many checkboxes as appropriate. Eachcorresponding value will be sent to the script, along with the nameof the checkbox set. As you can see in the example on the next page, the label for acheckbox comes after the input element. This means that you willoften need to style the label for a checkbox separately.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 39 Dr. Mark Llewellyn

Notice that the label for the checkbox comesafter the input element. Also notice that thelabel text does not need to match the valueattribute. This is because the label textidentifies the checkboxes to the visitor in thebrowser, whereas the value identifies the datato the script.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 40 Dr. Mark Llewellyn

Text Areas Text areas are used when you want to provide your visitor room towrite questions or comments. There is no value attribute with text areas. The value instead isthe text that appears between the start and end textarea tags. Visitors can enter up to 32,700 characters in a text area (themaximum number of characters allowed). Scroll bars will appearautomatically when needed, depending on the size of the text areaand the number of characters the visitor has entered. The attributes rows and cols set the height of the textarea inrows and the width of the textarea in columns respectively. Theattribute maxlength (new in HTML5) sets the upper limit on thenumber of characters that can be entered in the textarea.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 41 Dr. Mark Llewellyn

In this case, the height of the textarea willbe 8 rows and the width will be 50 characters.If the user enters more text than 8 rows,vertical scrollbars will appear at that point intime.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 42 Dr. Mark Llewellyn

The visitorhas enteredan amount oftext equal tothe size ofthe textarea.No scrollbarsappear yet.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 43 Dr. Mark Llewellyn

The visitorhas enteredmore textthan the sizeof the box (inrows) so theverticalscrollbar hasappeared.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 44 Dr. Mark Llewellyn

In this case themaxlengthattribute is set to20. As soon asthe visitor hasentered 20characters, nomore text can beentered.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 45 Dr. Mark Llewellyn

Calendar And Time Controls A common issue web developers have to deal with is how tocreate calendar widgets that allow the users to pick a date from acalendar so they do not have to enter the date themselves. In the past, creation of such a widget always required JavaScript,but with HTML5 the need to use JavaScript is disappearing. HTML5 has several new input types that create different calendarand time controls. Currently, not all browsers support these newtypes. Opera has the best and most elaborate support followedby Safari and Chrome. For the examples that follow, I’ve usedOpera 19.0 to demonstrate these new input types.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 46 Dr. Mark Llewellyn

Date and Datetime The new HTML5 input type date allows the user to select acalendar date. In Opera, a calendar with a date picker is provided. In Safari ascrollable element is provided that defaults to the current date. The HTML5 input type datetime generates a calendar alongwith a time selector with the time being UTC. The HTML5 input type datetime-local is identical todatetime except that the time is based on your local time(whatever is considered local time by your computer). These are all illustrated on the next few pages.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 47 Dr. Mark Llewellyn

A portion of the markup for the following examples. Notice in particularthe new input element types. Also notice that these forms are fordisplay purposes only and are not being processed so no method oraction attributes are specified.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 48 Dr. Mark Llewellyn

Notice the differences in the input boxes for the threedifferent input types. Date provides only a date,while datetime provides a date and time area, but isdesignated UTC, and datetime-local drops the UTCdesignation. Next pages illustrate them in action.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 49 Dr. Mark Llewellyn

dateCalendar widgetis displayedallowing the userto select a date.Note scrollableyear and month.Plus a “today”button to selecttoday’s date.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 50 Dr. Mark Llewellyn

datetimeCalendar widgetis displayedallowing the userto first select adate. Then thescroll arrowsallow you to goforward andbackward in time.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 51 Dr. Mark Llewellyn

datetime-localCIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 52 Dr. Mark Llewellyn

monthCalendar looksthe same but theuser can onlyselect an entiremonth of days(note highlightingof the days).CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 53 Dr. Mark Llewellyn

weekCalendar looksthe same but theuser can onlyselect a week(note highlightingof the weeks plusthe week numberappears in thecalendar).CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 54 Dr. Mark Llewellyn

Date and Datetime There are two new attributes, min and max that can be used torestrict the values for dates and times of the widget. For a date, if you wanted to make sure the user could not pick adate to far in the past, the min attribute would be set. Similarly,to make sure that they cannot enter a date too far in the future,the max attribute would be set. The values would have theformat: YYYY-MM-DD. For times, similar restrictions are allowed but the format for atime is HH:MM.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 55 Dr. Mark Llewellyn

Number Selectors The new number input type is used to allow the user to enter anumber, again, without them being required to type the number. It accepts only numbers, otherwise, a validation error is returned. It allows the min and max attributes to be specified to limit therange of values that can be selected. It also allows for another new attribute, step, which allows youto specify the increment values that can be entered. An example is shown on the next page.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 56 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 57 Dr. Mark Llewellyn

The up/down arrow keysallow the user to scrollthrough the availablenumbers until their desirednumber is selected.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 58 Dr. Mark Llewellyn

Sliding Numeric Selectors The new range input type generates a slider control. It has notext area for the user to type into, and like the number inputtype, it can use the min, max, and step attributes. In the past, with HTML4 or XHTML, including such a formcontrol would have required JavaScript to be able to generate andcontrol the widget. There is limited control over how the slider looks because at themoment the controls are browser-specific. However, you canapply a height and width to the range control. If you specify aheight larger than the width, the control renders vertically insteadof the default horizontal rendering.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 59 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 60 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 61 Dr. Mark Llewellyn

Color Selectors The new color input type allows the user a choice of somebasic colors with the options of entering a hex value or using acolor picker, similar to what is used in many software packages. The only desktop browser that currently supports this input typeis Opera 11 . The next couple of pages illustrate this input type.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 62 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 63 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 64 Dr. Mark Llewellyn

Creating An Autocomplete Feature With listand datalist The datalist element is new in HTML5. Combined with thelist attribute, it is used to provide a predefined list of options,making the process of creating a list seem like an autocompleteform. User’s don’t necessarily have to choose from the predefinedoptions, they can type their own answers if they wish. The datalist is similar to a select element. However, witha select element, the user cannot type their own option if theyneed to do so. The next two pages illustrate this new element.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 65 Dr. Mark Llewellyn

Insert codesection of miniform 3 herethat illustratesthe datalistelementCIS 4004: Web Based IT (Inside HTML5 – Part 4)Output fromshowform.php script(i.e., the processed datafrom the form)Page 66 Dr. Mark Llewellyn

Rendering of thedatalist element asuser is seeing the list.Notice option for them totype in their own value inthe text box.CIS 4004: Web Based IT (Inside HTML5 – Part 4)Page 67 Dr. Mark Llewellyn

CIS 4004: Web Based IT (Inside HTML5 –Part 4) Page 8 Dr. Mark Llewellyn Using forms often requires