Javascript program to add two numbers using textbox

The task is to write a JavaScript program to take two numbers from two different input boxes and show the sum of these two numbers as a result.

To achieve that let’s first create two different input boxes and a paragraph to show their sum as a result:

Enter First Number:  <input type="text" id="num1"><br><br>
Enter Second Number: <input type="text" id="num2"><br><br>
<button onclick="calcSum()">Show Result</button>
<p id="result"></p>

Now, let’s create the function calcSum() which will calculate the sum of the two numbers and show it as a result:

function calcSum(){
    let num1 = Number(document.getElementById('num1').value);
    let num2 = Number(document.getElementById('num2').value);
    
    let sum = num1 + num2;
    
    let result = document.getElementById('result');
    result.innerText = 'The sum is: '+ sum; 
}

The above code will produce the following result:

Javascript program to add two numbers using textbox

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts