javascript - 如何使用 Values 使输入复选框更新价格总计 + 包括总计的附加费用?

所以我制作了这个基本的复选框价格应用程序,每当您单击复选框选项时,它都会更新食品价格 https://codepen.io/shodoro/pen/GRQNXyq

但是,我不得不硬编码 javascript 中的价格,但我想知道如何根据输入标签中的 value 更新价格

因此,对于 index.html 中的这个示例,value 设置为 10,因此我无需在 JS 中硬编码 10 的价格,而是添加 value 属性

<input type="checkbox" name="item1" id="item1" value="10" onClick="updatePrice()">

另外,如何使我的代码可扩展?因为现在我手动编写了一堆 if else if else 语句,但是如果我要添加 50 个新菜单项,那么这对于我的 JS 代码来说是不可行的。

function updatePrice() {
        let price = 0.00;
        if (document.getElementById("item1").checked == true) {
            price = 10;
        }

        if (document.getElementById("item2").checked == true && document.getElementById("item1").checked == true) {
            price = 17;
        } else if(document.getElementById("item2").checked == true) {
            price = 7
        }

        if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true && document.getElementById("item2").checked == true) {
            price = 20;
        } else if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true) {
            price = 13
        } else if (document.getElementById("item3").checked == true && document.getElementById("item2").checked == true) {
            price = 10
        } else if (document.getElementById("item3").checked == true){
            price = 3
        }

        document.getElementById("price").innerText = "Your order total is: $" + price;
    }

最后,我有食物工作的基本总部分,但我不知道如何将我的 JS 代码转换为还包括运费、税金、小费百分比添加到最终总数中?

有任何想法吗?

回答1

你可以这样做...

const myForm = document.forms['my-form'];

myForm.reset();

myForm.oninput =_=>
  {
  let sum = 0;

  ['item1','item2','item3'].forEach( chkBxNm => 
    {
    if (myForm[chkBxNm].checked) sum += +myForm[chkBxNm].value
    })  

  myForm.total.textContent = `Your order total is: $${sum}`
  }

  myForm.onsubmit = e =>
  {
  e.preventDefault()  // disable submit
  }
label,
output {
  display: block;
  }
output {
  color      : green;
  font-size  : 1.4em;
  margin-top : 1.2em;
  }
<form action="" name="my-form">

  <label><input type="checkbox" name="item1" value="10">  12 piece wings $10</label>
  <label><input type="checkbox" name="item2" value="7">  6 piece wings $7</label>
  <label><input type="checkbox" name="item3" value="3">  Large fries $3</label>

  <output name="total">Your order total is: $0 </output>

</form>

或者

const myForm = document.forms['my-form'];

myForm.reset();

myForm.oninput =_=>
  {
  let sum = 0;

  myForm.querySelectorAll('input[type=checkbox]').forEach( chkBx => 
    {
    if (chkBx.checked) sum += +chkBx.value
    })  

  myForm.total.textContent = `Your order total is: $${sum}`
  }
myForm.onsubmit = e =>
  {
  e.preventDefault()  // disable submit
  }
label,
output {
  display: block;
  }
output {
  color      : green;
  font-size  : 1.4em;
  margin-top : 1.2em;
  }
<form action="" name="my-form">

  <label><input type="checkbox" value="10">  12 piece wings $10</label>
  <label><input type="checkbox" value="7">  6 piece wings $7</label>
  <label><input type="checkbox" value="3">  Large fries $3</label>

  <output name="total">Your order total is: $0 </output>

</form>

回答2

要从复选框的 value 属性中动态读取价格,并没有太多遗漏。所需要的只是读取相应元素的“value”属性。如果您只想一起计算价格,那么您只需要以下代码。

为您的复选框元素添加一个类。在这种情况下,它的类 item

<input type="checkbox" name="item1" id="item1" class="item" value="10" onClick="updatePrice()">

然后您可以使用类 item 遍历所有复选框并动态计算价格:

function updatePrice() {
    let price = 0.00;
    const checkboxes = document.getElementsByClassName("item");

    for(let i = 0; i < checkboxes.length; i++) {
        if(checkboxes[i].checked) price += Number(checkboxes[i].value);
    }

    document.getElementById("price").innerText = "Your order total is: $" + price;
}

回答3

这是此代码的简单解决方案 https://codepen.io/mallick-portfolio/pen/KKQNbZZ?editors=1010 您可以添加更多复选框来自动计算价格。

js在这里

function updatePrice() {
let price = 0.00;
const checkboxes = document.getElementsByClassName("item");
for(let i = 0; i < checkboxes.length; i++) {
    if(checkboxes[i].checked) price += parseInt(checkboxes[i].value);
}

document.getElementById("price").innerText = "Your order total is: $" + price;

} 更新价格()

回答4

  1. 总价由输入的 value 更新。
  2. 我根据您告诉的 data 数组创建 JS。

    因此,您不必担心数据的长度。
  3. 我不确定我写的总价公式是你想要的,但你可以看到总价也更新了。您可以更改 priceOption 对象的详细信息选项。
const data = ["12 piece wings $10", "6 piece wings $7", "Large fries $3"];
const priceOption = {
  tax: 0.1,
  deliveryFee: 5,
  tip: 0.2
};
let foodPrice = 0;

const $menuItems = document.querySelector(".menu-items");
$menuItems.addEventListener("click", (e) => updatePrice(e));

data.map((item, idx) => {
  const [name, price] = item.split("$");
  const menu = `
    <div class="menu-item">
      <input type="checkbox" name="item${idx}" id="item${idx}" value=${price} class="item">
      <label for="item${idx}">
        ${name} 
        $<span class="itemPrice">${price}</span>
      </label>
     </div>
    `;
  $menuItems.innerHTML += menu;
});

function updatePrice(e) {
  const $itemPrice =
    e.target.querySelector(".menu-item input.item") ||
    e.target.closest(".menu-item input.item");
  if (!$itemPrice) return;
  const $foodPrice = document.querySelector(".foodPrice");
  const $totalPrice = document.querySelector(".totalPrice");

  const price = +$itemPrice.value;
  const isChecked = $itemPrice.checked;

  foodPrice = isChecked ? foodPrice + price : foodPrice - price;
  const totalPrice =
    foodPrice * (1 + priceOption.tax + priceOption.tip) +
    priceOption.deliveryFee;
  $foodPrice.textContent = `$${foodPrice}`;
  $totalPrice.textContent = `$${totalPrice}`;
}
.foodPrice {
  font-weight: bold;
  color: green;
  font-size: 24px;
}
<div>
  <h2>Order Details</h2>
  <div class="menu-items"></div>
</div>
<div class="payment">
  <h2>Payment Summary</h2>
  <p>Food Total <span class="foodPrice">$0.00</span></p>
  <p>Tax 10%</p>
  <p>Delivery Fee $5.00</p>
  <p>Tip (20%)</p>
  <p>Your order total is: <span class="totalPrice">$0.00</span></p>
</div>

相似文章

随机推荐

最新文章