If you can guarantee that the input tags come as groups of four and contains no other input tags then you could do something like this:
Code:
<form id="form1">
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" /><br />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
</form>
<script type="text/javascript">
function addEvent(els, type, func) {
if(!(els instanceof Array)) els = [els];
for(var i=0, n=els.length; i<n; ++i) {
if(els[i].addEventListener) els[i].addEventListener(type, func, false);
else els[i].attachEvent("on"+type, func);
}
}
String.prototype.trim = function() {
return this.replace(/^\s+/, "").replace(/\s+$/, "");
};
var fields = document.getElementById("form1").getElementsByTagName("input");
for(var i=0, n=fields.length; i<n; i+=4) {
addEvent(
[fields[i], fields[i+1]],
"keyup",
(function(i) {
return function(e) {
var vcost = fields[i].value.trim();
var vcharge = fields[i+1].value.trim()
var ncost = vcost*1;
var ncharge = vcharge*1;
if(vcost=="" || vcharge=="" || isNaN(ncost) || isNaN(ncharge)) {
fields[i+2].value = fields[i+3].value = "";
return;
}
fields[i+2].value = ncharge - ncost;
fields[i+3].value = (ncharge - ncost) * 100 / ncharge;
};
})(i)
);
}
</script>
I admit, this is a bit grungy, but I don't have time to create to create prettier code.
Bookmarks