简体   繁体   English

Javascript客户端饮料价格计算器

[英]Javascript Client-Side Beverage Price Calculator

I'm working on a personal project where I'd like to take user input via a form's text boxes, perform a calculation on it, and display the result on the same page. 我正在一个个人项目中,我想通过表单的文本框接受用户输入,对其进行计算,然后在同一页面上显示结果。 I work in a restaurant and would like to simplify the process of calculating the cost of a cocktail. 我在一家餐厅工作,想简化计算鸡尾酒费用的过程。 I'm new to Javascript and this is my first proper project. 我是Java的新手,这是我的第一个适当的项目。 I'm having difficulty figuring out what to do after storing the user input into a variable. 将用户输入存储到变量后,我很难弄清楚该怎么做。 I have created an object "drinkPrices" with the three different categories of drink types under the "name" keyword, the respective prices under the other keywords, and then a method that calculates the prices. 我已经创建了一个对象“ drinkPrices”,在“名称”关键字下具有三种不同类别的饮料类型,在其他关键字下具有了各自的价格,然后创建了一种计算价格的方法。 I'm unsure if this approach is correct and ANY feedback/suggestions/help would be much appreciated. 我不确定这种方法是否正确,任何反馈/建议/帮助将不胜感激。

Main difficulties: 1. Am I storing the user input correctly? 主要困难:1.我是否正确存储了用户输入? 2. How do I take the user input and reference it to the method in the object I have created? 2.如何获取用户输入并将其引用到我创建的对象中的方法? 3. How do I display the results of the calculation on the page? 3.如何在页面上显示计算结果?

    <!DOCTYPE html>
<html lang="en">
<head>
    <script src="submitAlert.js"></script>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="theform">
    Enter Spirit Name:<br>
    <input type="text" id="sname" name="spiritname"><br>
    Enter Spirit Amount (in ounces):<br>
    <input type="text" id="samount" name="spiritamount">
    <br><br>
    <input type="submit" value="submit" onclick="return foo();" />
</form>
</body>
<p id="outputarea"> ...Output area is right here...</p>
</html>

Javascript: 使用Javascript:

var drinkPrices =  {
    name: ['rail', 'call', 'premium'],
    railPrice:  4,
    callPrice: 6,
    premiumPrice: 8,
    quantity: 0,
    calculatePrice: function() {
        if (name === 'rail') {
            calculatePrice = quantity * railPrice;
        } else if (name === 'call') {
            calculatePrice = quantity * callPrice;
        } else if (name ==='premium') {
            calculatePrice = quantity * premiumPrice;
        }
        return this.calculatePrice;
    }

} //this is the code I have for when the user hits submit. } //这是我点击用户提交时的代码。 I am missing a lot// 我很想念//

function foo() {
    var a = document.getElementById("sname").value;
    var b = document.getElementById("samount").value;

    alert("Submit button clicked!");
    return true;
}

Just use a name-price map: 只需使用名称-价格映射:

 const price = {
    rail:2,
    call:4,
    premium:6
 };

Then you can simply get the price: 然后,您可以简单地获取价格:

 function calculatePrice() {
   const name = document.getElementById("sname").value;
   const amount = document.getElementById("samount").value;

   alert(`It costs ${amount * prices[name]}`);
 }

Hint: Don't use a form if you dont want to send something to the server (just use <input> only), it makes things complicated, and give appropriate names to variables and functions! 提示:如果您不想将某些内容发送到服务器(仅使用<input> ),则不要使用表单,它会使事情变得复杂,并为变量和函数指定适当的名称!

Here are some improvements for your further coding: Replace input elements with select lists when you dealing with a predefined list of options, in this way you prevent accedential typos by the user. 这是您进一步编码的一些改进:在处理选项的预定义列表时,用select列表替换input元素,这样可以防止用户输入错字。
When you use select and you're only interessted in corresponding values, use the value attribute on option tags. 当您使用select并且仅对相应的值感兴趣时,请在option标签上使用value属性。
When you need numerical inputs, use <input type="number"> or <input type="range" min="0" max="100" step="1"> (min/max/step are optional and can be added to number-inputs too). 当您需要数字输入时,请使用<input type="number"><input type="range" min="0" max="100" step="1"> (min / max / step是可选的,可以是也添加到数字输入中)。
Use the onsubmit on forms instead of onclick on buttons to let the browser validate the inputs (part of better practice). 在表单上使用onsubmit而不是在按钮上onclick ,可以使浏览器验证输入(更好的做法的一部分)。

Here I've hacked together an example: 在这里,我总结了一个示例:

 document.querySelector('#theform').addEventListener('submit', function(e) { e.preventDefault(); let price = this.spirit.value * 1; let amount = this.spiritamount.value * 1; let total = (price * amount).toFixed(2); document.querySelector('#outputarea').textContent = total; }); 
 <form id="theform"> Enter Spirit Name:<br> <select name="spirit"> <option value="4">rail</option> <option value="6">call</option> <option value="8">premium</option> </select><br> Enter Spirit Amount (in ounces):<br> <input type="number" name="spiritamount" value="1"> <br><br> <button>Calculate</button> </form> <p id="outputarea">0.00</p> 

Here is another example with listed entries: 这是列出条目的另一个示例:

 let receipt = {}; const prices = { 'rail': 4, 'call': 6, 'premium': 8 }; // clear the receipt document.querySelector('#reset').addEventListener('click', function(e) { e.preventDefault(); receipt = {}; document.querySelector('#outputarea').innerHTML = ''; }); document.querySelector('#theform').addEventListener('submit', function(e) { e.preventDefault(); let spirit = this.spirit.value; let amount = this.spiritamount.value * 1; if(spirit in receipt) { receipt[spirit] += amount; } else { receipt[spirit] = amount; } let list = ''; let total = 0; for(const e in receipt) { let sum = prices[e] * receipt[e]; list += `<div>${e} x ${receipt[e]} = ${sum.toFixed(2)}</div>`; total += sum; } list += `<hr>${total.toFixed(2)} ¤`; document.querySelector('#outputarea').innerHTML = list; }) 
 <form id="theform"> Select Spirit: <select name="spirit"> <option>rail</option> <option>call</option> <option>premium</option> </select><br> Enter Spirit Amount (in ounces): <input type="number" name="spiritamount" value="1"><br><br> <button>Add to receipt</button> or <button id="reset">Reset</button> </form> <p id="outputarea"></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM