From a short review;
You should declare your variables with
const
orlet
There is a ton of copy-pasted code in there
'commission-field'
is not a great name for your element, I would just call itcommission
Avoid writing multiple calls to
document.getElementById
for the same idIts hard to control what users enter, and sometimes
parseFloat
returns a NaN, I would always deal with that pro-activelyI would create a function that formats an element like
function cleanAmountElement(id){ const elementValue = document.getElementById(id); const cleanerValue = parseFloat(elementValue*1).toFixed(2); const cleanestValue = IsNaN(cleanerValue)?0:cleanerValue; document.getElementById(id).value = IsNan(cleanerValue)?0:cleanerValue;cleanestValue; return cleanerValue;cleanestValue; }
Note that this is not super super clean, that function both updates the UI and returns a value :/
Then you can do something funky with functional programming where you pass a list of ids and process them
const sum = ['salary', 'commission', 'rental', 'other_income'].map(cleanAmountElement) .reduce(getSum,0); function getSum(a,b){ return a+b; }