Calculate Average Number Automatically Using JavaScript
Submitted by razormist on Thursday, July 2, 2020 - 13:53.
In this code we will try to create Calculate Average Number Automatically using JavaScript. The program will calculate the entered number and display the average. The trick of this code is to get the sum of all numbers and divide the numbers base on total number. To learn more about this, just follow the steps below.
There you have it we successfully created a Calculate Average Number Automatically using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting started:
First you have to download bootstrap framework, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- </head>
- <body>
- <nav class="navabar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted;"/>
- <div class="col-md-4">
- <div class="form-group">
- <input type="number" id="grade1" onkeyup="getAverage();" class="form-control"/>
- </div>
- <div class="form-group">
- <input type="number" id="grade2" onkeyup="getAverage();" class="form-control"/>
- </div>
- <div class="form-group">
- <input type="number" id="grade3" onkeyup="getAverage();" class="form-control"/>
- </div>
- <div class="form-group">
- <input type="number" id="grade4" onkeyup="getAverage();" class="form-control"/>
- </div>
- <div class="form-inline">
- <input type="text" class="form-control" id="result" readonly="readonly"/>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. The code can auto calculate the total value of the input forms. To do this just copy and write these block of codes inside the text editor, then save it as script.js inside the js folder.- function getAverage(){
- var grade1=document.getElementById('grade1').value;
- var grade2=document.getElementById('grade2').value;
- var grade3=document.getElementById('grade3').value;
- var grade4=document.getElementById('grade4').value;
- var total;
- var ave;
- if(grade1 !="" && grade2 !="" && grade3 !="" && grade4 !=""){
- total=parseInt(grade1)+parseInt(grade2)+parseInt(grade3)+parseInt(grade4);
- ave=total/4
- document.getElementById('result').value=ave.toFixed(0);
- }
- }
Add new comment
- 2253 views