How can JavaScript be used to automatically calculate and display sums of input fields in a PHP form?

To automatically calculate and display sums of input fields in a PHP form, you can use JavaScript to listen for changes in the input fields, calculate the sum, and display it in a designated output field. This can be achieved by adding an event listener to the input fields that triggers a function to calculate the sum and update the output field.

<form>
  <input type="number" id="num1" oninput="calculateSum()">
  <input type="number" id="num2" oninput="calculateSum()">
  <input type="number" id="sum" readonly>
</form>

<script>
function calculateSum() {
  var num1 = parseInt(document.getElementById('num1').value) || 0;
  var num2 = parseInt(document.getElementById('num2').value) || 0;
  var sum = num1 + num2;
  document.getElementById('sum').value = sum;
}
</script>