」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 JavaScript 建立房間成本估算器

使用 JavaScript 建立房間成本估算器

發佈於2024-11-03
瀏覽:262

这个估算器会做什么?

  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:根据日期计算房价

接下来,我们根据入住日期房间类型计算每晚房价。旺季(六月至八月)的费率较高,其余时间则较低。

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 对象从入住日期中提取月份。
  • 旺季(六月至八月):这几个月的价格较高。
    • 大号床间和特大号床间:每晚 250 美元。
    • 套房:每晚 350 美元。
  • 淡季(一年中的剩余时间):价格较低。
    • 大号床间和特大号床间:每晚 150 美元。
    • 套房:每晚 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() 函数计算每晚的房价。
  • 总房费:我们将房价乘以住宿天数,得到折扣前的总房费。
  • 应用折扣:如果用户选择AAA/SeniorMilitary,我们将应用折扣(分别为10%或20%)。
  • 税费:我们在折扣房费的基础上加收 12% 的税费。
  • 显示结果:页面上显示总费用(带明细)供用户查看。

结论

  • 1.获取表单值:当用户提交表单时,代码首先从表单中获取所有输入值(姓名、入住日期、入住天数等)。
  • 2.验证入住率:脚本检查客人数量是否超过房间的最大入住率,如果超过则显示错误。
  • 3.计算房间费用:根据所选的房间类型和入住日期,脚本计算每晚房价,将其乘以住宿天数,然后应用所有折扣。
  • 4.加税:脚本在折扣房费的基础上加收 12% 的税。
  • 5.显示结果:最终成本(包含明细)在结果部分中向用户显示。

就是这样!我们使用 JavaScript 构建了一个简单但实​​用的 房间成本估算器

此代码的我的 GitHub 存储库在这里!包括页面的基本 HTML 和 Bootstrap 样式

作者

Building a Room Cost Estimator with JavaScript

Thounny Keo

创意开发人员和设计师

前端开发学生 |联年联


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