🧭

[JavaScript]BMIを計算するプログラムを作成 (備忘録)

に公開

1.はじめに

HTML/CSS/JavaScript の理解を深めるために、BMIを計算するプログラムを作成しました。
他のエンジニアが作成したソースコードを読みながら、作成しました。

2.サンプルプログラム

Sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <!--HTML5より前の文字コードの指定方法 -->
    <meta http-equiv="content-type" content="text/html; charset=Shift_JIS">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <div class="container">
        <div class="panel">
            <h1 class="text-center">BMI計算</h1>
            <form>
                <div id="inputWeight">
                    <p>体重をKg単位で入力してください</p>
                    <input class="no-ui" id="weight" type="number" placeholder="体重を入力してください" required />
                </div>
                <div id="inputHeight">
                    <p>身長をcm単位で入力してください</p>
                    <input class="no-ui" id="height" type="number" placeholder="身長を入力してください" required />
                </div>
                <button type="button" class="btn" onclick="bmiCalc()">BMIを計算</button>
            </form>
            <div id="result" class="text-center"></div>
    	</div>
    </div>
    <script src="main.js"></script>
</body>
stylesheet.css
body {
    text-align: center;
}

form {
    background-color: #fff;
    padding: 20px;
    color: #000;
}

form p {
    margin-bottom: 3px;
}

form p:nth-child(1){
    margin-top: 0;
    background-color: lightblue;
}

input {
    width: 100%;
    padding: 5px 5px;
    border: 2px solid black;
    margin-top: 5px;
    margin-bottom: 10px;
    background-color: white;
    font-size: 14px;
}

/* 入力フォームがクリックされた際の装飾 */
input:focus {
    border: 3px solid lightblue;
}

button {
    background-color: white;
}

/* ボタン上にカーソルを合わせた際の装飾 */
button:hover {
    background-color: lightblue;
    color: white;
}

/* 入力フォームのスピンボタン(数値入力UI)を非表示にする */
.no-ui {
    -moz-appearance: textfield; 
} 
  .no-ui::-webkit-outer-spin-button, 
  .no-ui::-webkit-inner-spin-button { 
    -webkit-appearance: none; 
}

.btn {
    margin-bottom: 10px;
    margin-left: auto;
    margin-right: auto;
    display: block;
}

/* スクリーンサイズが768px以上の場合の装飾 */
@media (min-width: 768px) {
    .panel {
        width: 50%;
        margin-left: auto;
        margin-right: auto;
    }
}

/* スクリーンサイズが1024px以上の場合の装飾 */
@media (min-width: 1024px) {
    .panel {
        width: 30%;
        margin-left: auto;
        margin-right: auto;
    }
}
main.js
function bmiCalc() {
	// valueは文字列型のため、BMI計算前に数値型に変換
	let weight = Number(document.getElementById("weight").value);
	let height = Number(document.getElementById("height").value);

	// 入力値がNull/空文字か検証
	if (!weight || !height) {
		document.getElementById("result").innerHTML = "数値を入力してください。";
		// エラーが検出された場合、JavaScript内の後続処理を実行せず終了
		return;
	}

	// 入力値が0以下か検証
	if (weight <= 0 || height <= 0) {
		document.getElementById("result").innerHTML = "0以上の数値を入力してください。";
		// エラーが検出された場合、JavaScript内の後続処理を実行せず終了
		return;
	}

	// 入力された身長をメートルに換算
	let heightInMeters = height / 100;
	let bmi = weight/(heightInMeters * heightInMeters);
	// 小数点以下第一位に丸める
	bmi = bmi.toFixed(1);

	let calcResult;
	if (bmi <= 18.4) {
		calcResult = `あなたのBMIは${bmi}です。標準体重を下回っています。`;
	} else if (bmi >= 18.5 && bmi <= 24.9) {
		calcResult = `あなたのBMIは${bmi}です。標準体重です。`;
	} else if (bmi >= 25 && bmi <= 29.9) {
		calcResult = `あなたのBMIは${bmi}です。標準体重を上回っています。`;
	} else {
		calcResult = `あなたのBMIは${bmi}です。肥満です。`;
	}

	document.getElementById("result").innerHTML = calcResult;
}

・操作画面

3.実行環境

・OS: Windows 11(バージョン 24H2)
・ブラウザ: Microsoft Edge(バージョン 135.0.3179.66)
・エディタ: Visual Studio Code(バージョン 1.99.2)

3.参考

使用ソースコード
Chapter04 文字コードと文字化け対策
input type=”number” の代わりにinputmode=”numeric” を使用する
メディアクエリの書き方(min-width, max-width)
【WEB制作の基本】nth-childとnth-of-typeでよく使う倍数や範囲の逆引き集
数値を固定小数点数形式で文字列に変換する(toFixed)
[JavaScript]null または空文字判定
Number(),parseInt(),parseFloat()のちがい

Discussion