[Risolto] Sum Numbers in HTML with JavaScript and DOM

  

3
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:
sum numbers in html with javascript

1 risposta
2

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>
Condividi: