使用多个变量计算旅程成本的总价

时间:2015-03-05 15:30:05

标签: javascript html math percentage

好的,所以我必须记录用户输入的成人人数,并将其与我已经获得的旅行费用相比,但是我还需要考虑孩子的数量,并给他们平均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语句?谢谢你的任何建议!

3 个答案:

答案 0 :(得分:1)

减少20%与乘以.8相同,所以:

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

答案 1 :(得分: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;
}

答案 2 :(得分:0)

您的问题是&#34;我如何计算知道成人人数和孩子数量的总价格&#34;?也许尝试(Adult+0.8*Children)*price之类的东西(但我认为你能够自己找到它......)

您唯一需要考虑的是,如果用户没有输入成人人数或子女数量(可能设为Children0,您会怎么做?如果document.getElementById("ofChild").value="",例如。)

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