3
07/11/2024 1:04 pm
Argomento iniziale
Write a JS function that reads two numbers from input fields in a web page and puts their sum in another field when the user clicks on a button.
Input/Output:
There will be no input/output, your program should instead modify the DOM of the given HTML document.
Sample HTML:
<input type="text" id="num1" /> + <input type="text" id="num2" /> = <input type="text" id="sum" readonly="readonly" /> <input type="button" value="Calc" onclick="calc()" /> <script> function calc() { // TODO: sum = num1 + num2 } </script>
Examples:
1 risposta
2
07/11/2024 1:04 pm
Here is the solution:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="text" id="num1"/> + <input type="text" id="num2"/> = <input type="text" id="sum" readonly="readonly"/> <input type="button" value="Calculate the sum" onclick="calc()"/> <script> function calc() { let num1 = Number(document.querySelector("#num1").value); let num2 = Number(document.querySelector("#num2").value); let sum = num1 + num2; document.getElementById("sum").value = sum; } </script> </body> </html>