Created a HTML form and Javascript to calculate the sum of different expense fields and display it in the sum field. But the sum is not changing dynamically
Sum of different expense fields to be calculated dynamically and to be displayed in the SUM field.
But the sum is not happening
function calculateSum() {
// Get the values of the input fields
const field1 = parseFloat(document.getElementById('food').value) || 0;
const field2 = parseFloat(document.getElementById('travel').value) || 0;
const field3 = parseFloat(document.getElementById('recharge').value) || 0;
const field4 = parseFloat(document.getElementById('grocery').value) || 0;
const field5 = parseFloat(document.getElementById('others').value) || 0;
// Calculate the sum
const sum = field1 + field2 + field3 + field4 + field5;
// Update the sum field with the calculated value
document.getElementById('sumField').value = sum;
}
body {
background-color: lime;
}
<form action="recordexpense.jsp">
<table align="center">
<th>
<h2>Enter your Expense</h2>
</th>
<tr>
<td>Food : </td>
<td><input type="number" name="food" value="food" oninput="calculateSum()"></td>
</tr>
<tr>
<td>Travel :</td>
<td> <input type="number" name="travel" value="travel" oninput="calculateSum()"></td>
</tr>
<tr>
<td>Mobile/DTH/OTT recharge : </td>
<td><input type="number" name ="recharge" value="recharge" oninput="calculateSum()">
</td>
</tr>
<tr>
<td>Grocery :</td>
<td> <input type="number" name ="grocery" value="grocery" oninput="calculateSum()"></td>
</tr>
<tr>
<td>Others :</td>
<td> <input type="number" name ="others" value="others" oninput="calculateSum()"></td>
</tr>
<tr>
<td>Sum: </td>
<td><input type="number" name="sumField" readonly></td>
</tr>
<tr>
<td><input type="Submit" name="Submit"></td>
</tr>
</table>
</form>