In this example I’ll show you how to add two numbers in javascript using textbox.
Write a program in JavaScript to create a function for the sum of two numbers entered by user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <!doctype html> <html> <head> <title>Code4Examples</title> <meta charset="utf-8"> <style> label{ display: block; } </style> </head> <body> <h1 id="msg"></h1> <label for="num1">Number 1: <input type="text" id="num1"> </label> <label for="num2">Number 2: <input type="text" id="num2"> </label> <button id="add">Add Numbers</button> <script> //get inputs and button element from document var num1El=document.querySelector("#num1"); var num2El=document.querySelector("#num2"); var addBtn=document.querySelector("#add"); var msgEl=document.querySelector("#msg"); //bind a function tothe onClick event the AddBtn addBtn.onclick=function(){ //add two numbers sum=Number(num1.value)+ Number(num2.value); //write the sum into #msg document msgEl.innerHTML=sum; } </script> </body> </html> |
Output:
[…] Add Two Numbers in JavaScript […]