「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > JavaScript を使用して部屋料金見積りツールを構築する

JavaScript を使用して部屋料金見積りツールを構築する

2024 年 11 月 3 日に公開
ブラウズ:876

この推定ツールは何をしますか?

  1. ユーザーが部屋のタイプ (クイーン、キング、またはスイート) を選択できるようにします。
  2. ユーザーが滞在したい泊数を選択できるようにします。
  3. 割引を適用します (例: AAA/シニア、軍事)。
  4. 宿泊料金を計算し、税金を適用して合計金額を表示します。

STEP_1: フォーム送信の処理

まず、ユーザーがフォームに送信した内容をキャプチャする必要があります。 JavaScript を使用して、フォームの送信時にページが更新されないようにすることで、入力を失わずに計算を処理できるようにします。

document.getElementById("costForm").addEventListener("submit", function (event) {
    event.preventDefault(); // Prevents the page from reloading

    // 1. Get the values from the form
    const name = document.getElementById("name").value;
    const checkInDate = document.getElementById("checkInDate").value;
    const nights = parseInt(document.getElementById("nights").value);
    const roomType = document.querySelector('input[name="roomType"]:checked').value;
    const discount = document.querySelector('input[name="discount"]:checked').value;
    const adults = parseInt(document.getElementById("adults").value);
    const children = parseInt(document.getElementById("children").value);

    // 2. Check room occupancy
    const maxOccupancy = getMaxOccupancy(roomType);
    if (adults   children > maxOccupancy) {
        document.getElementById("messageDiv").innerText = `The room you selected cannot hold your group. Max occupancy is ${maxOccupancy}.`;
        return;
    }

    // 3. Clear previous messages and calculate the cost
    document.getElementById("messageDiv").innerText = "";
    calculateCost(roomType, checkInDate, nights, discount);
});

内容:

  • フォーム送信: フォームは「submit」イベントをリッスンし、event.preventDefault() によってページの更新が防止されるため、JavaScript で入力を処理できます。
  • フォームの値の取得: ユーザーの名前、宿泊数、部屋のタイプなどの値をフォームから取得します。
  • 客室定員チェック:宿泊者数が客室の最大宿泊人数を超えているかどうかをチェックする機能を使用しています。存在する場合は、エラー メッセージが表示されます。

STEP_2: 最大収容人数を確認する

それでは、各部屋タイプに何人宿泊できるかを確認する関数を作成してみましょう。ホテルの客室には収容できるゲストの数に制限があるため、この機能は重要です。

function getMaxOccupancy(roomType) {
    if (roomType === "queen") {
        return 5; // Queen rooms can hold up to 5 people
    } else if (roomType === "king") {
        return 2; // King rooms can hold up to 2 people
    } else if (roomType === "suite") {
        return 6; // 2-Bedroom Suites can hold up to 6 people
    }
}

内容:

  • 部屋タイプ: 各部屋タイプ (クイーン、キング、スイート) の最大宿泊人数は異なります。
    • クイーンルーム: 最大宿泊人数は5名です。
    • キングルーム: 最大宿泊人数は2名です。
    • スイート: 最大宿泊人数は6名です。
  • 大人と子供の数が制限を超える場合、エラーが表示され、計算が停止されます。

STEP_3: 日付に基づいて宿泊料金を計算する

次に、チェックイン日部屋タイプに基づいて 1 泊あたりの宿泊料金を計算します。料金はハイシーズン (6 月から 8 月) には高く、その他の期間には低くなります。

function getRoomRate(checkInDate, roomType) {
    const date = new Date(checkInDate); // Convert the check-in date to a Date object
    const month = date.getMonth()   1; // Get the month (months are 0-indexed)

    let rate; // Variable to store the room rate

    // High season (June to August) rates are more expensive
    if (month >= 6 && month 



内容:

  • 日付計算: JavaScript Date オブジェクトを使用して、チェックイン日から月を抽出します。
  • ハイシーズン (6 月 - 8 月): この月の間は料金が高くなります。
    • クイーンルームとキングルーム: 1泊あたり250ドル。
    • スイート: 1 泊あたり 350 ドル。
  • オフシーズン(年末): 料金は安くなります。
    • クイーンルームとキングルーム: 1泊あたり150ドル。
    • スイート: 1泊あたり210ドル。

STEP_4: 総費用の計算

最後に、滞在費の総額を計算します。割引を適用し、税金を追加して最終合計を算出します。

function calculateCost(roomType, checkInDate, nights, discount) {
    // 1. Get the room rate per night
    const roomRate = getRoomRate(checkInDate, roomType);

    // 2. Calculate the total room cost before discounts
    let totalRoomCost = roomRate * nights;

    // 3. Apply the discount (if any)
    let discountRate = 0; // Start with no discount
    if (discount === "aaa") {
        discountRate = totalRoomCost * 0.1; // 10% discount for AAA/Senior
    } else if (discount === "military") {
        discountRate = totalRoomCost * 0.2; // 20% discount for Military
    }

    // Subtract the discount from the total room cost
    const discountedCost = totalRoomCost - discountRate;

    // 4. Calculate the tax (12% of the discounted total cost)
    const tax = discountedCost * 0.12;

    // 5. Calculate the final total cost, including tax
    const totalCost = discountedCost   tax;

    // 6. Display the results on the page
    document.getElementById("result").innerHTML = `
        

Room Rate per Night: $${roomRate.toFixed(2)}

Number of Nights: ${nights}

Discount Amount: $${discountRate.toFixed(2)}

Tax: $${tax.toFixed(2)}

Total Cost (with tax): $${totalCost.toFixed(2)}

`; }

内容:

  • 宿泊料金: getRoomRate() 関数を使用して 1 泊あたりの宿泊料金を計算します。
  • 宿泊料金合計: 宿泊料金に宿泊数を乗算して、割引前の合計料金を算出します。
  • 割引の適用: ユーザーが AAA/シニア または ミリタリー を選択した場合、割引が適用されます (それぞれ 10% または 20%)。
  • 税金: 割引された客室料金に 12% の税金が加算されます。
  • 結果の表示: ユーザーが確認できるように、合計コスト (内訳付き) がページに表示されます。

結論

  • 1.フォーム値の取得: ユーザーがフォームを送信すると、コードはまずフォームからすべての入力値 (名前、チェックイン日、宿泊数など) を取得します。
  • 2.占有数の検証: スクリプトはゲストの数が部屋の最大占有数を超えているかどうかをチェックし、超えている場合はエラーを表示します。
  • 3.客室料金の計算: 選択した部屋のタイプとチェックイン日に基づいて、スクリプトは 1 泊あたりの料金を計算し、宿泊数を乗じて、割引を適用します。
  • 4.税金の追加: スクリプトは、割引された客室料金に 12% の税金を追加します。
  • 5.結果の表示: 最終コスト (内訳付き) が結果セクションにユーザーに表示されます。

それで終わりです! JavaScript を使用して、シンプルでありながら機能的な Room Cost Estimator を構築しました。

このコードの GitHub リポジトリはここにあります。ページの基本的な HTML およびブートストラップ スタイルを含む

著者

Building a Room Cost Estimator with JavaScript

サニー・ケオ

クリエイティブ デベロッパー & デザイナー

フロントエンド開発学生 |イヤーアップユナイテッド


Building a Room Cost Estimator with JavaScript

リリースステートメント この記事は次の場所に転載されています: https://dev.to/thounny/building-a-room-cost-estimator-with-javascript-45h7?1 侵害がある場合は、[email protected] に連絡して削除してください。
最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3