"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > JavaScript로 객실 비용 추정기 구축

JavaScript로 객실 비용 추정기 구축

2024-11-03에 게시됨
검색:815

이 추정기는 어떤 역할을 합니까?

  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);
});

기능:

  • 양식 제출: 양식은 "제출" 이벤트를 수신하고 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. 결과 표시: 결과 섹션에 최종 비용(구분 포함)이 사용자에게 표시됩니다.

그리고 그게 다야! 우리는 자바스크립트를 사용하여 간단하면서도 기능적인 객실 비용 견적기를 구축했습니다.

이 코드에 대한 내 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에서 복제됩니다.1 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3