使用基于选项列表值和变量的javascript计算订单价格?

时间:2018-04-23 11:27:24

标签: javascript html

我想从以下计算总订单价格:

由选项列表值确定的特定项目的编号*设置该项目的成本

共有3个项目,这就是我现在的计算结果但不起作用(单击按钮时没有任何反应):

function calculate();
{

        var mugPrice = 5;
        var keyringPrice = 2;
        var tshirtPrice = 15;

        var numMug = document.getElementById('numberOfMugs').value
        var numTshirt = document.getElementById('numberOfTshirts').value
        var numKeyring = document.getElementById('numberOfKeyrings').value

        var totalpay = (numMug * mugPrice) + (numTshirt * tshirtPrice) + (numKeyring * keyringPrice);

        document.getElementById('totalPrice').value= totalpay;      
}

这就是我的按钮和字段的样子:

<button class="calcButton" onclick="calculate()">Calculate Order</button>
<h3>Total price: <input type=text; id="totalPrice" disabled /> </h3>

numMug,numTshirt和numKeyring是选项列表的ID,其值对应于某人希望购买的商品数量

不确定我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

您需要删除分号:

function calculate();
                    ^

'use strict';
function calculate() {
    var mugPrice = 5,
        keyringPrice = 2,
        tshirtPrice = 15,
        numMug = +document.getElementById('numberOfMugs').value || 0,
        numTshirt = +document.getElementById('numberOfTshirts').value || 0,
        numKeyring = +document.getElementById('numberOfKeyrings').value || 0,
        totalpay = (numMug * mugPrice) + (numTshirt * tshirtPrice) + (numKeyring * keyringPrice);

    document.getElementById('totalPrice').value = totalpay;
}
Mugs: <input type="input" id="numberOfMugs"><br>
T-Shirts: <input type="input" id="numberOfTshirts"><br>
Keyrings: <input type="input" id="numberOfKeyrings"><br>

<button type="button" class="calcButton" onclick="calculate()">Calculate Order</button>
<h3>Total price: <input type="text" id="totalPrice" disabled /></h3>