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.

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()" />
    function calc() { 
       // TODO: sum = num1 + num2

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">
    <meta charset="UTF-8">

<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()"/>

    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;



answered by user andrew