settingsAccountsettings
Menusettings

Q: Sum Numbers in HTML with JavaScript and DOM

+2 votes

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

 

asked in JavaScript category by user ak47seo

1 Answer

+1 vote

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>

 

answered by user andrew
...