summaryrefslogtreecommitdiff
path: root/javascript/03-calculator/index.html
blob: fc2398b9397cc8f6b0d6aeccd9be62962554d186 (plain)
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
<!DOCTYPE html>
<html>

<head>
    <title>Calculator</title>
</head>

<body>
  <h1>Calculator</h1>
  
  Number 1: <input type="text" id="num1" value="0"/><br/>
  Number 2: <input type="text" id="num2" value="0"/><br/>
  
  <button onclick="calculate()">Add</button><br/>

  Result: <span id="resultArea"></span>
  
  <script>
    const addButton = document.getElementById("addButton");
    const resultArea = document.getElementById("resultArea");
    
    function calculate() {
      // 1. Fetch values from the text fields using their IDs
      let value1 = document.getElementById("num1").value;
      let value2 = document.getElementById("num2").value;

      // 2. Convert strings to floating-point numbers
      let number1 = parseFloat(value1);
      let number2 = parseFloat(value2);

      // 3. Handle empty fields or invalid inputs (fallback to 0)
      if (isNaN(number1)) number1 = 0;
      if (isNaN(number2)) number2 = 0;

      // 4. Perform math addition
      let sum = number1 + number2;

      // 5. Output the final sum to the page
      resultArea.innerText = sum;
    }
  </script>
</body>

</html>