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>
Keywords
Related Questions
- What is the best practice for sorting data stored in a text file using PHP?
- How can PHP be used to create structured arrays from complex data structures found in a text file, like in the provided example?
- How can form data be properly processed and saved to the database in Symfony2 controllers after validation?