Sum of Two number using html ,javascript ,css Dom Exercise

Sum of Two number using html ,css , javascript Dom

In this blog we will learn about dom exercise in which we will take input two number and sum them. It is beginner friendly exercise


Output of the Program: 





Note : make sure HTML and javascript files are in the same folder

Html Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="number" id="a">
    <input type="number" id="b">
    <button id="sum"  onclick="plus()">Sum</button> // calling a function to add sum
//when button is clicked
    <div id="result">sum is: </div>
    <script src="script1.js"></script> // javascript file use in the code
</body>
</html>


Javascript Code:

Save javascript filename as script1.js else it will not work


function plus(){
// get the variable from the document
    let a = Number(document.getElementById('a').value);
    let b = Number(document.getElementById('b').value);
    let r = Number(a+b); // sum of two numbers
    document.getElementById("result").textContent=`sum is:  ${r}`
};

Post a Comment

0 Comments