Code:
function calculateValue(form) {
var controls = form.elements,
match = /^(\d+)\.(\d+)$/.exec(controls.userinput.value),
months;
if (!match) {
/* Validation failed */
return;
}
months = (match[1] * 12) + Number(match[2]);
controls.calculated.value = months - controls.dbvalue.value;
}
A validating form of my earlier function.

Originally Posted by
mhodgson
function calcFrm(el){ This obviously sets the function (does (el) mean this element-userinput ?)
It will be whatever is passed when the function is called, but in John's previous post, yes, it's the userinput form control.
var frm=el.form.elements; This sets a string variable frm to save code typing
No, it assigns an object reference to the variable, frm. The elements property is a collection (think array) of controls within a form. You got the reason partially right, though: not only does it save typing, it's quicker as the script interpreter doesn't have to perform so many property accessor operations.
for (var i = 0, vals=el.value.split('.'); i < 2; i++) This sets splits the variable vals and puts it into an array with two values
vals[i]=vals[i]? vals[i]*(i? 1 : 12) : 0; I Know what this does but don't understand the process
This is a rather convoluted way of writing:
Code:
var vals = el.value.split('.');
if (vals[0]) vals[0] = vals[0] * 12;
else vals[0] = 0;
if (vals[1]) vals[1] = vals[1] * 1;
else vals[1] = 0;
The conditional operator (? :) is somewhat like an expression form of an if statement.
  cond ? expr1 : expr2
The first expression, cond, is evaluated as a boolean. If true, the entire expression evaluates to expr1. If false, the expression evaluates to expr2.
vals[2]=frm['dbvalue'].value*1; This gets the value from the db field (but why *1??)
The value property of form controls is always a string. There are many ways to convert a string to number, including multiplying by one (1). However, it's not the best way. Either use unary plus:
Code:
vals[2] = +frm.dbvalue.value;
or the Number constructor function:
Code:
vals[2] = Number(frm.dbvalue.value);
frm['calculated'].value=isNaN(i=vals[0] + vals[1] - vals[2])? '' : i; This calculates the 'calculated' value but I'm not too sure of the process - why isNan?
}
Simplified, this is equivalent to:
Code:
var value = vals[0] + vals[1] - vals[2];
if (isNaN(value)) frm.calculated.value = '';
else frm.calculated.value = value;
/* or:
* frm.calculated.value = isNaN(value) ? '' : value;
*/
If one of the string-to-number conversions fails, it will yield the special number value, NaN. Therefore, using the isNaN function is a simple form of error detection. However, using regular expressions to validate input before beginning work on it (as in my code above) is generally a better approach.
Hope that helps,
Mike
Bookmarks