Building a form where values can be entered in either pounds or kilos.
Script is...
function onlyNumber(fld) {
if(fld.value.match(/[^0-9.]/)) {
fld.value=fld.value.replace(/[^0-9.]/g,'');
}
}
function convertUnit(sense, value) {
retValue = 0;
if (isNaN (value)) { alert ('Non-numeric value'); return 0; }
value = parseFloat (value);
var factor = 0.4536;
if (sense == 'kg2lb') {
retValue = value/factor;
retValue = Math.round(retValue);
}
else if (sense == 'lb2kg') {
retValue = value*factor;
retValue = Math.round(retValue);
}
return retValue;
}
Works fine but I have to repeat this on every input:
onblur="this.form.kg_va.value=convertUnit('lb2kg',this.value);"
onkeyup="onlyNumber(this);" onfocus="if(this.value == '0') { this.value = ''; }"
Is there some way to simplify the onblur
code ?
For example, is there a way to have the function focus on the same var pairs? The var pair being lb_FOOBAR
and kg_FOOBAR
.
And what about the input functions that are exactly the same?
onkeyup="onlyNumber(this);" onfocus="if(this.value == '0') { this.value = ''; }"
Any way to avoid having to repeat them for each input? Form will have 12 fields.
onlyNumber
assumes a.
for decimal notation. This is not true for most of the world. You could add some logic to that function to do a better guess. Some info \$\endgroup\$