HTML5 Guidelines for Web Developers

(coco) #1
3.4 Client-Side Form Validation 57

function updateSum() {
var ips = document.getElementsByTagName("input");
var sum = 0;
var prods = 0;
for (var i=0; i<ips.length; i++) {
var cnt=Number(ips[i].value);
if (cnt > 0) {
sum += cnt * Number(document.getElementById(
ips[i].name+"Price").innerHTML);
prods += cnt;
}
}
document.getElementById("sumProd").value = prods;
document.getElementById("sum").value = sum;
}


We get the product price directly from the table by using the innerHTML value
of the relevant table column and converting it to a number with the JavaScript
function Number(). The same applies to the value in the input field (ips[i].
value), because without this conversion, JavaScript would add up the character
strings, which would not produce the desired results. The calculated values are
then inserted into the value attributes of the output elements.


3.4 Client-Side Form Validation


One of the advantages of the new elements and attributes in forms is that the
user can now enter data much more easily (for example, choose the date from a
calendar). Another great advantage is the option of checking the form contents
before the form is submitted and alerting the user of any mistakes. You might say
that kind of checking is rather old hat because it has been around for years. That
is true, but until now this step always had to be done via JavaScript code that
you had to program. Thanks to jQuery and similar libraries, this task has become
much easier and the code is more manageable, but you still must depend on an
external library.


With HTML5, this situation changes fundamentally: You define the parameters
of the input fields in HTML, and the browser checks whether the fields have been
filled in correctly. That is a big step forward and makes many lines of JavaScript
code redundant. This tiny example will convince you:





Free download pdf