-
Notifications
You must be signed in to change notification settings - Fork 1
/
avg.html
56 lines (51 loc) · 2.69 KB
/
avg.html
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
46
47
48
49
50
51
52
53
54
55
56
<html>
<head>
<title>Average Calculator</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,700" rel="stylesheet" type="text/css">
<link href="style.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-85225251-1', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript">
function go(first, second) {
if (first && second && first*1 == first && second*1 == second) {
// First, check that the variables exist.
// Then, multiply them by one to convert them from strings to numbers, and compare them to the original variables, which are still strings.
// If they're actual numbers, the comparison with type conversion (two equals signs instead of three) will say true (one is a number and the other is a string, but one of them can be converted, so they can be compared).
// If numbers were not entered, the "*1" will convert one side to "NaN" (not a number) and make the comparison say false.
document.getElementById("weight").innerHTML = "Weighted Average of " + first + " and " + second + ": <span class='highlight'>" + Math.round((first*6 + second*3)/9) + "</span>";
document.getElementById("avg").innerHTML = "Average of " + first + " and " + second + ": <span class='highlight'>" + Math.round((first*1 + second*1)/2) + "</span>";
// The "*1" is needed here again. If it was just "first + second", the "+" would do a concatenation instead of addition, so, for example, 1+2 is 12 instead of 3
} else {
document.getElementById("weight").innerHTML = "";
document.getElementById("avg").innerHTML = "Please enter numbers in both boxes";
}
}
</script>
<style type="text/css">
#avg, #weight {
}
.highlight {
font-weight: bold;
text-decoration: underline;
}
</style>
</head>
<body>
<form action="javascript:go(document.getElementById('first').value, document.getElementById('second').value);">
<label for="first">First Number (weighs 2/3): </label><input type="number" id="first" />
<br>
<label for="second">Second Number (weighs 1/3): </label><input type="number" id="second" />
<br>
<input type="submit" value="Calculate Average" />
</form>
<p id="avg"></p>
<p id="weight"></p>
</body>
</html>