For context, I'm building a JS calculator whereby the values displayed dynamically change in a 'summary box' as the user changes the values in the input fields (using a <form> element).
I have set default values in the <input> elements of the form, but the calculation functions in the summary box only get called as a keyup function when the values in the input fields are changed.
I have managed to get this to work perfectly, however, on page load the summary box values do not change as this is based on the keyup function (which hasn't occurred yet), so even though there are default values in the inputs, the summary box has nothing to calculate from (as it's waiting for the keyup functions to execute).
Now, I have found a workaround by repeating the DOM blocks to replace values on page load, but the code isn't very DRY. I am sure there must be a way to do this. I have tried to put the code block in an array and/or object but I am unable to successfully extract and execute this.
// THESE ARRAY ITEMS REPRESENT THE INPUT FIELDS IN THE HTML
const innerElementsArr = [investment, buying, selling, invFee];
// APPLYING THE DOM CHANGES TO EACH INPUT ELEMENT ABOVE
innerElementsArr.forEach(item => {
item.onkeyup = function() {
invDisplay.innerText = `£${investment.value}`;
netProfit.innerText = `£${grossProfitLoss()}`;
invFeeDisplay.innerText = `£${withInvFee()}`;
netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;
};
});
// DISPLAY ALL CALCULATIONS ON PAGE LOAD
invDisplay.innerText = `£${investment.value}`;
netProfit.innerText = `£${grossProfitLoss()}`;
invFeeDisplay.innerText = `£${withInvFee()}`;
netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;
As you can see, I am repeating myself and would like to know if there is a much more cleaner way to do this.
Thank you in advance.
Thank you to Ouroborus for the answer - it was such a simple workaround.
I created a function including the DOM block and then called that function as a keyup event and a window.onload event.
const valuesToChange = () => {
invDisplay.innerText = `£${investment.value}`;
coinDisplay.innerText = `${coinsOwned()} BTC`;
netProfit.innerText = `£${grossProfitLoss()}`;
invFeeDisplay.innerText = `£${withInvFee()}`;
exitFeeDisplay.innerText = `£${withExitFee()}`;
netProfitLossDisplay.innerText = `£${netProfitDisplay()}`;
};
// CHANGING THE VALUES IN THE SUMMARY AREA
const innerElementsArr = [investment, buying, selling, invFee, exitFee];
innerElementsArr.forEach(item => {
item.onkeyup = function() {
valuesToChange();
};
});
// DISPLAY ALL CALCULATIONS ON PAGE LOAD
window.onload = function() {
valuesToChange();
};