首页 > 解决方案 > 使用单选按钮计算

问题描述

我正在尝试使用单选按钮创建此 JavaScript 计算。因此,如果用户选中“送货到家庭地址”,那么 5.99 英镑的价值将被添加到总框中,但如果用户选择其他单选按钮,则不会显示任何价格。我对 JavaScript 很陌生,所以我可能会遇到一些错误,但如果您能帮助我,我将不胜感激

<section id="collection">
                <h2>Collection method</h2>
                <p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
                <p>
                Home address - &pound;5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked>&nbsp; | &nbsp;
                Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
                </p>
            </section>
Total <input type="text" name="total" size="10" readonly>

JavaScript

let totalPrice = 0;
var RadioBtn = document.getElementById ('input[name=deliveryType]');

radioBtn.addEventListener("click", function() {
  if(radioBtn.clicked) {
   totalPrice += parseFloat(radioBtn.dataset.price)
  total.value = " + totalPrice;
}
}

标签: javascripthtml

解决方案


以下是我对提供的代码的观察:

  1. radioBtn 变量是用 Pascal Case(第一个字母大写)声明的,因此它不会在代码中被引用,因为其他行使用 camelCase(以小写开头)。更改为 camelCase 并在整个代码中坚持使用它。
  2. 您的选择器 - getElementById 用于 Id,它将返回一个元素,因为您传递的是查询选择器 'input[name=deliveryType]' 而代码不会找到您要查找的元素
  3. 由于您希望将单击事件添加到单选按钮,因此您可以使用 getElementsByName 并提供单选按钮的名称。然后遍历生成的元素以应用单击事件...这样,两个单选按钮都将调用单击。
  4. 无需检查是否在点击事件中点击,您已经知道它只会在点击时被调用,而是您可以添加事件参数来获取点击目标及其信息以根据需要应用它。

例子:

    let totalPrice = 0;
    let radioBtns = document.getElementsByName('deliveryType');
    let totalEl = document.getElementsByName ('total')[0];


    radioBtns.forEach(function(element, index){
      element.addEventListener("click", function(event){
       totalPrice += parseFloat(event.target.dataset.price); //remove += if the price should be the same everytime, replace with = or it will add the number to the total when clicked
       totalEl.value = totalPrice  +  " totalPrice";
     });
  });

https://jsfiddle.net/dn4x7oy9/8/


推荐阅读