-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
53 lines (49 loc) · 1.41 KB
/
script.js
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
let equal_pressed = 0;
//Refer all buttons excluding AC and DEL
let button_input = document.querySelectorAll(".input-button");
//Refer input,equal,clear and erase
let input = document.getElementById("input");
let equal = document.getElementById("equal");
let clear = document.getElementById("clear");
let erase = document.getElementById("erase");
window.onload = () => {
input.value = "";
};
//Access each class using forEach
button_input.forEach((button_class) => {
button_class.addEventListener("click", () => {
if (equal_pressed == 1) {
input.value = "";
equal_pressed = 0;
}
//display value of each button
input.value += button_class.value;
});
});
//Solve the user's input when clicked on equal sign
equal.addEventListener("click", () => {
equal_pressed = 1;
let inp_val = input.value;
try {
//evaluate user's input
let solution = eval(inp_val);
//True for natural numbers
//false for decimals
if (Number.isInteger(solution)) {
input.value = solution;
} else {
input.value = solution.toFixed(2);
}
} catch (err) {
//If user has entered invalid input
alert("Invalid Input");
}
});
//Clear Whole Input
clear.addEventListener("click", () => {
input.value = "";
});
//Erase Single Digit
erase.addEventListener("click", () => {
input.value = input.value.substr(0, input.value.length - 1);
});