计算出具有多个变量的旅程成本的总价

Working out total price of Journey cost with multiple variables

本文关键字:的旅程 变量 计算      更新时间:2023-09-26

好的,所以我必须计算用户输入的成年人人数,并将其乘以我的旅程成本,但我也需要计算儿童人数,并在所有旅程中为他们提供统一的20%折扣率,这是我的代码。

HTML

<select id = "journeyList">
<option name ="Bristol " value="40">Bristol - Newcastle</option>
<option name ="London " value="35" >Bristol - London</option>
<option name ="Glasgow " value="70" >Glasgow - Manchester</option>
</select><br><br>
Number of Adults: 
<form>
<input type = "number" name ="adult" id="ofAdults" value="" required><br>
Number of Children:<br>
<input type = "number" name ="child" id="ofChild" value="" required>
<button type="button" onclick="BookingFare(); return false;">Submit</button><br>
    Journey Price:
    <div id="priceBox"></div><br>
    Number of Adults:
    <div id="adultsBox"></div><br>
    Number of Children:
    <div id="childBox"></div><br>
    Total Cost:
    <div id="totalBox"></div>

Javascript

function BookingFare() { 
    var journeyList = document.getElementById("journeyList");
    var price =journeyList.options[journeyList.selectedIndex].value;
    var Adults = document.getElementById("ofAdults").value;
    var Children = document.getElementById("ofChild").value;
    //var total = price * Adults;
    document.getElementById('priceBox').innerHTML = price;
    document.getElementById('adultsBox').innerHTML = Adults;
    document.getElementById('childBox').innerHTML = Children;
    document.getElementById('totalBox').innerHTML = total;
}

我应该找做if语句吗?谢谢你的建议!

减少20%等于乘以.8,因此:

document.getElementById('totalBox').innerHTML =
   (Adults * price) + (Children * price * .8);

您的问题是"在知道成年人和儿童数量的情况下,我如何计算总价"吗?也许可以试试(Adult+0.8*Children)*price之类的东西(但我认为你自己就能找到。)

你唯一需要考虑的是,如果用户没有输入成年人或儿童人数的数字,你会怎么做(例如,如果document.getElementById("ofChild").value="",可以将Children设置为0。)

您还可以问自己如何处理错误的输入(字母等)

这是修改后的JS文件:

function BookingFare() { 
    var journeyList = document.getElementById("journeyList");
    var price =journeyList.options[journeyList.selectedIndex].value;
    var Adults = document.getElementById("ofAdults").value;
    var Children = document.getElementById("ofChild").value;
    var total = price * Adults + (price - (price * 0.2) *  Children);
    document.getElementById('priceBox').innerHTML = price;
    document.getElementById('adultsBox').innerHTML = Adults;
    document.getElementById('childBox').innerHTML = Children;
    document.getElementById('totalBox').innerHTML = total;
}