0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】関数とイベントを使って「入場料計算ツール」を作ってみました

0
Posted at

1. 今回のミッション:年齢別に入場料を表示する

ユーザーが年齢を入力して「確認」ボタンを押すと、以下の基準で入場料を表示するプログラムを作ります。

0 ~ 7歳: 無料(未就学児)

8 ~ 13歳: 5,000ウォン(小学生)

14 ~ 19歳: 10,000ウォン(青少年)

20 ~ 64歳: 15,000ウォン(成人)

65歳 ~: 7,000ウォン(シニア)

2. 大切なポイント:データ型の変換

ここで一番注意が必要なのは、「inputタグから取得した値は、見た目が数字でも最初は『文字列(String)型』である」 という点です。

そのまま計算しようとすると、"20" + "20""2020" になってしまいます。
そのため、比較演算や計算を正しく行うために Number() 関数を使って 「数値(Number)型」 に変換する作業が必要です。

「確認」ボタンを押した時に実行される関数 checkPrice() の中身です。

function checkPrice() {
    // 1. 入力された値を取得
    const age = document.getElementById("age").value;
    const result = document.getElementById("result");

    // 2. 文字列型を数値型に変換(重要!)
    let ageNum = Number(age);

    let price = "";

    // 3. 条件文(if - else if)で判定
    if (ageNum < 8) {
        price = "無料 (未就学児)";
    } else if (ageNum < 14) {
        price = "5,000ウォン (小学生)";
    } else if (ageNum < 20) {
        price = "10,000ウォン (青少年)";
    } else if (ageNum < 65) {
        price = "15,000ウォン (成人)";
    } else {
        price = "7,000ウォン (シニア)";
    }

    // 4. 結果を画面に出力
    result.innerHTML = "入場料は " + price + " です。";
    result.style.color = "blue";
}

4. まとめ

onclick: ボタンをクリックした時に特定の関数を呼び出す仕組みを学びました。

value: 入力フォームの中身を取り出す時に使います。

型変換: Number(age) のように型を合わせないと、思った通りの結果にならないことを実感しました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?