먼저 사용자가 양식에 제출하는 내용을 캡처해야 합니다. 양식이 제출될 때 페이지가 새로 고쳐지는 것을 방지하기 위해 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); });
이제 각 객실 유형에 몇 명이 숙박할 수 있는지 확인하는 함수를 만들어 보겠습니다. 호텔 객실에는 수용할 수 있는 손님 수에 제한이 있기 때문에 이 기능은 중요합니다.
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 } }
다음으로 체크인 날짜와 객실 유형을 기준으로 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기능:
마지막으로 총 숙박 비용을 계산합니다. 할인을 적용한 다음 세금을 추가하여 최종 총액을 얻습니다.
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)}
`; }
그리고 그게 다야! 우리는 자바스크립트를 사용하여 간단하면서도 기능적인 객실 비용 견적기를 구축했습니다.
이 코드에 대한 내 GitHub 저장소가 여기에 있습니다! 페이지의 기본 HTML 및 부트스트랩 스타일 포함
토니 케오
크리에이티브 개발자 및 디자이너
프론트엔드 개발 학생 | 올해의 유나이티드
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3