BMIの判定器 【JavaScriptのサンプルコード】
ここでは、当社の新人研修受講者に向けて、JavaScriptのサンプルコードを紹介しています。
BMIの判定器のサンプルコード
身長と体重からBMI(Body Mass Index)を判定します。
<!DOCTYPE html> <html> <head> <title>BMI</title> <meta charset="UTF-8"> <script> function calculate() { var h = document.getElementById("height").value; var w = document.getElementById("weight").value; var r = Math.round((w / (h * h)) * 10) / 10; var comment; var color; if (Number.isNaN(r)) { comment = " please enter correctly "; color = "red"; } else if (r < 18.5) { comment = " You are in the underweight."; color = "blue"; } else if (r < 25) { comment = " You are in the normal range."; color = "green"; } else { comment = " You are in the overweight."; color = "yello"; } document.getElementById('result').style.color = color; document.getElementById('result').textContent = "Your BMI is " + r + comment; } </script> </head> <body> <h1>Body Mass Index</h1> Height(m):<input id ="height"/><br> Weight(kg):<input id ="weight"/><br> <p><button onclick="calculate()">calculate</button></p> <p id ="result" ></p> </body> </html>