-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (69 loc) · 2.41 KB
/
index.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
// converting pounds to kg
function poundsToKg(pounds) {
kilograms = pounds / 2.205;
return kilograms;
}
// converting inches to meters
function inchesToM(inches) {
centimeters = (inches * 2.54) / 100;
return centimeters;
}
function calculateBMI() {
// defining variables corresponding to the needed DOM elements
const radioPounds = document.getElementById("radioPounds");
const radioKgs = document.getElementById("radioKgs");
const radioCms = document.getElementById("radioCms");
const radioInches = document.getElementById("radioInches");
const weightInput = Number(document.getElementById("weightInput").value);
const heightInput = Number(document.getElementById("heightInput").value);
const result = document.getElementById("result");
// declaring the bmi value before calculation
let bmi;
// making sure the user selects units
if (
(!radioPounds.checked && !radioKgs.checked) ||
(!radioCms.checked && !radioInches.checked)
) {
result.textContent = "Please select units!";
} else if (heightInput <= 0 || weightInput <= 0) {
result.textContent = "Enter valid numbers!"; // making sure the user puts valid values (greater than 0)
} else {
if (radioKgs.checked) {
// kg + cm
if (radioCms.checked) {
bmi = weightInput / (heightInput / 100) ** 2;
}
// kg + pounds
else {
bmi = weightInput / inchesToM(heightInput) ** 2;
}
} else if (radioPounds.checked) {
// pounds + cm
if (radioCms.checked) {
bmi = poundsToKg(weightInput) / (heightInput / 100) ** 2;
}
// pounds + inches
else {
bmi = poundsToKg(weightInput) / inchesToM(heightInput) ** 2;
}
}
// showing the result in different colors based on bmi value
let index;
let colors = ["#c0a330", "#3db120", "#e07426", "#e31f18"];
let comments = ["underweight", "normal weight", "overweight", "obesity"];
if (bmi < 18.5) {
index = 0;
} else if (bmi <= 24.9) {
index = 1;
} else if (bmi <= 29.9) {
index = 2;
} else {
index = 3;
}
// range information for different bmi values is taken from https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/index.html
result.textContent = `BMI: ${bmi.toFixed(1)}. Weight status: ${
comments[index]
}.`;
result.style.color = colors[index];
}
}