首页 > 解决方案 > 从输入中获取用户输入(数字)

问题描述

我正在尝试为我正在从事的项目制作价格计算器。用户应该选择他们想要的门票类型和数量。然后程序计算出总成本。

我在 JavaScript 中设置了门票价格。问题是我的代码没有识别出它是来自 HTML 输入元素的数字输入,因此它NaN作为总成本输出。我猜我的功能是错误的。

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <h1>Museum Ticket Pricing Application</h1>

        <label for="adults" id="adults">Number of Adults: </label>
        <input type="number" id="adults">
        <br>
        <br>
        <label for="children" >Number of Children: </label>
        <input type="number" id="children">
        <br>
        <br>
        <label for="under7" >Number of children under 7: </label>
        <input type="number" id="childrenUnder7">
        <br>        
        <br>
        <label for="senior" >Number of Seniors: </label>
        <input type="number" id="senior">
        <br>

        <Button id="totalBtn">Total Price</Button>
        <p></p>

        <script src="app.js" async defer></script>
    </body>
</html>

Javascript:

    let adults = document.getElementById("adults");

    let children = document.getElementById("children");

    let under7 = document.getElementById("childrenUnder7");

    let senior = document.getElementById("senior");


    const totalBtn = document.querySelector("button");

    const para = document.querySelector("p");


    let adultFee = 10;

    let childrenFee = 5;

    let under7Fee = 2;

    let seniorFee = 7;

    totalBtn.addEventListener("click", function totalPrice() {

       let adultsInput = adults.value;

       let childrenInput = children.value;

       let under7Input = under7.value;

       let seniorInput = senior.value;

       let totalcalculation = adultsInput * adultFee + childrenInput * childrenFee + under7Input * under7Fee + seniorInput * seniorFee;

       totalcalculation;

       para.textContent = "the total price is " + totalcalculation;
});

标签: javascriptecmascript-6

解决方案


问题在这里:

<label for="adults" id="adults">Number of Adults: </label>
<input type="number" id="adults">

你已经复制id="adults"了,所以let adults = document.getElementById("adults");实际上是重新调整你的标签而不是输入。只需从中删除id="adults"<label for="adults" id="adults">Number of Adults: </label>它应该可以正常工作。


推荐阅读