I have a project that involves finding the largest value among 3 numbers. My goal is to input 3 numbers into the designated fields and then, upon clicking the Calculate button, display the biggest number after the main heading (h1). I am converting the inputs into numbers and creating an array out of them. Then, I loop through the array to compare each element with the first one in order to determine the maximum value. However, the code seems to be not working and I can't seem to identify the mistake. Would appreciate any help on this?
Here is the HTML structure:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Max Value Of Three Numbers</title>
</head>
<body>
<h1>The biggest number is: <span id="maxDisplay">0</span></h1>
<input type="number" name="" id="num1">
<input type="number" name="" id="num2">
<input type="number" name="" id="num3">
<button id="calculateMax">Calculate</button>
<script type="text/javascript" src="maxValue.js"></script>
</body>
</html>
And here's the JavaScript part:
var maxDisplay = document.querySelector("#maxDisplay");
var number1 = document.getElementById("num1");
var num1 = Number(number1.value);
var number2 = document.getElementById("num2");
var num2 = Number(number2.value);
var number3 = document.getElementById("num3");
var num3 = Number(number3.value);
var arr = [num1, num2, num3];
var calculateMax = document.getElementById("calculateMax");
var maxNumber = 0;
calculateMax.addEventListener("click", function(){
var maxNumber = arr[0];
for (var i = 1; i < arr.length; i++)
{
if(arr[i] > maxNumber)
{
maxNumber = arr[i];
}
}
maxDisplay.textContent = maxNumber;
});