Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
65 lines (52 loc) · 2.13 KB
/
Copy pathscript.js
File metadata and controls
65 lines (52 loc) · 2.13 KB
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
57
58
59
60
61
62
63
64
65
/*
*caldulate() is called when the user clicks any operation button.
*It reads the two numbers, validates them, does the maths, and displays the result.
*The paramets "opertion" is a string: 'add', 'subtract', 'multiplt', or 'divide'.
*/
function calculate(operation) {
// 1. GET REFFERENCES TO TML ELEMENTS ---
var resultDisplay = document.getElementById("result");
var errorDisplay = document.getElementById("error");
// Clear any previous error message
errorDisplay.textContent = "";
resultDisplay.textContent = "";
// 2. READ USER'S INPUT ---
var input1 = document.getElementById("number1").value;
var input2 = document.getElementById("number2").value;
// 3. DATA VALIDATION ---
// CHeck if either field is empty
if (input1 === "" || input2 === "") {
errorDisplay.textContent = "Please enter both numbers.";
return; //stop the function here
}
//Convert the text input into actual numbers
var num1 = Number(input1);
var num2 = Number(input2);
// Check if the conversion was successful (i.e., the input was a valid number)
if (isNaN(num1)) {
errorDisplay.textContent = "The first input is not a valid number. Please enter valid numbers.";
return; //stop the function here
}
if (isNaN(num2)) {
errorDisplay.textContent = "The second input is not a valid number. Please enter valid numbers.";
return; //stop the function here
}
// 4. PERFORM THE ARITHMETIC ---
var answer;
if (operation === "add") {
answer = num1 + num2;
} else if (operation === "subtract") {
answer = num1 - num2;
} else if (operation === "multiply") {
answer = num1 * num2;
}else if (operation === "divide") {
// Extra check: cannot divide by zero
if (num2 === 0) {
errorDisplay.textContent = "Cannot divide by zero. Please enter a non-zero number for the second input.";
return; //stop the function here
}
answer = num1 / num2;
}
// --- 5. SHOW THE RESULT ---
resultDisplay.textContent = answer + " :)";
}