As a beginner in JavaScript, I have been studying event listeners and how to apply them to my code. I am currently working on a basic calculator project where users input two amounts into HTML fields for addition. Although my current code functions correctly, it does not update the total amount when the field values change. This is why I believe I need an event listener. Can you guide me on how to implement this in my scenario? I have reviewed online examples but still struggle with the concept.
Should I incorporate some of my code within a function?
Note: It's important that my global variable "paytotal" always displays the most up-to-date results so I can access this data across my page.
Below is my existing JavaScript:
var payamount1 = document.getElementById("amount1").value;
var payamount2 = document.getElementById("amount2").value;
var paytotal = Number(payamount1) + Number(payamount2);
document.getElementById("payment-due").innerHTML = paytotal;
This is what my HTML looks like:
<input type="text" id="amount1" placeholder="enter amount 1">
<input type="text" id="amount2" placeholder="enter amount 2">
<div class="details-row">Total payable: <span id="payment-due"></span></div>