-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
84 lines (68 loc) · 2.4 KB
/
main.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//Initialize some default variables
var x = document.getElementById('xInput'),
y = document.getElementById('yInput'),
msg = document.getElementById('msg'),
result1 = document.getElementById('result1'),
result2 = document.getElementById('result2');
function xOut(input){
xInput = input.value;
//Set value of X in the sum to input X
document.getElementById('sum1X').innerHTML = document.getElementById('sum2X').innerHTML = xInput;
//If length of the input is less than 0 e.g. nothing set the value back to X
if(xInput.length <= 0) {
document.getElementById('sum1X').innerHTML = document.getElementById('sum2X').innerHTML = 'X';
}
//Validate input
validate(xInput, x);
}
function yOut(input){
yInput = input.value;
//Set value of Y in the sum to input Y
document.getElementById('sum1Y').innerHTML = document.getElementById('sum2Y').innerHTML = yInput;
//If length of the input is less than 0 e.g. nothing set the value back to Y
if(yInput.length <= 0) {
document.getElementById('sum1Y').innerHTML = document.getElementById('sum2Y').innerHTML = 'Y';
}
//Validate input
validate(yInput, y);
}
//Validate function takes input value and the element the input came from
function validate(input, element){
var element1 = element,
input1 = input,
element2,
input2;
if(element1.id == 'xInput') {
element2 = y;
input2 = y.value;
} else {
element2 = x;
input2 = x.value;
}
if(input1.length >= 0 && isNaN(input1) || input1 % 1 !== 0 || isNaN(input2) || input2 % 1 !== 0) {
element1.setAttribute("class", "error");
msg.innerHTML = "The value must be an integer.";
result1.innerHTML = result2.innerHTML = 'Z';
} else {
element1.className = element2.className = '';
msg.innerHTML ='';
}
}
//Calculations and results
function calc(){
//Initially set the input values to false
var xInput = false,
yInput = false;
if(x.className != 'error') {
xInput = x.value;
}
if(y.className != 'error') {
yInput = y.value;
}
if(xInput && yInput){
result1.innerHTML = parseInt(xInput) + parseInt(yInput);
result2.innerHTML = parseInt(xInput) - parseInt(yInput);
} else {
result1.innerHTML = result2.innerHTML = 'Z';
}
}