HTML5 Guidelines for Web Developers

(coco) #1
3.5 Example: A Support Form 65

The HTML code for the form starts by loading an external JavaScript file and the
already familiar call window.onload:




The initEventListener function runs through all input elements and assigns an
anonymous function to the onchange event, checking the corresponding element
for its validity:


function initEventListener() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (!inputs[i].willValidate) {
continue;
}
inputs[i].onchange = function() {
this.checkValidity();
}
}
}


The event listener is only added if the element can check validity. In our example
the two buttons for submitting or saving do not have the option to check valid-
ity and therefore do not get an onchange event. As explained earlier, checking
the individual form fields after they have been filled in is more convenient than
checking the entire form with the oninput event.


To improve the form’s user friendliness, we want to emphasize the elements
marked as required to make it immediately clear to the user which are the most
important fields. Fortunately, we do not have to add an extra style to each element.
CSS3 gives us the new selector :required, which is intended for exactly this case.
The following instruction places an orange border around all required elements:


:required { border-color: orange; border-style: solid; }


The definition of the individual input fields does not contain any great surprises.
E-mail address and phone number have their own types and are required; the
date when the defect occurred has the type date and can therefore be selected
from a calendar window. The two-column layout in the upper part of the web-
page is achieved via adjacent div elements. We still want users who jump to the
next field using the Tab key to fill in the form from top to bottom and not, as

Free download pdf