首页 > 解决方案 > 用于从表单中添加复选框的 JavaScript 函数

问题描述

我之前的问题因拼写错误而关闭,但我不确定为什么,因为我的逻辑中存在更多问题。但是,我已经编辑了循环,但仍然无法正常工作。我需要添加多个项目并将答案输入文本框中,但是我似乎看不到问题。

JavaScript

<script>
"use strict";

const form = document.getElementById('bookingForm');
const total = form.getElementById('total');
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;

 document.getElementsByName('event[]')[0].onclick = function() {
    totalPrice()
};

function totalPrice(){
    let totalPrice = 0;
    for (let i=0; i< cbamount; i++) {
       const box = checkboxes[i];
       if (box.checked) {
          totalPrice += box.dataset.price;
       }//if
}//for
}


document.getElementsByName("txtTotalPrice").value = totalprice;  

文本框的 HTML

<section id="checkCost">
        <h2>Total cost</h2>
        Total <input type="text" name="total" size="10" readonly="">
    </section>

项目的 HTML(有多个)

<span class="eventTitle">Winter</span>
            <span class="eventStartDate">2020</span>
            <span class="eventEndDate">2020</span>
            <span class="catDesc">Fam</span>
            <span class="venueName">Disc</span>
            <span class="eventPrice">0.00</span>
            <span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00">

标签: javascripthtml

解决方案


有一些涉及案例的错误。

你使用form.getElementById而不是document.getElementById

form.querySelectorAll而不是相同document.querySelectorAll

另外,您正在使用getElementsByNamewhich 返回一个数组,因此仅返回 [0]。

进一步:您可能会发现返回是字符串的问题,并且额外的点击将附加到该字符串而不是添加为数字。

另外:您document.getElementsByName("txtTotalPrice").value = totalprice;在函数括号之外有 [SIC] ,因此没有在正确的时间调用它。

不过,该示例只需要很少的修复即可。

const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;

document.getElementsByName('event[]')[0].onclick = function() {
  totalPrice()
};



function totalPrice() {
  let totalprice = 0;
  for (let i = 0; i < cbamount; i++) {
    const box = checkboxes[i];
    if (box.checked) {
      totalprice += box.dataset.price;
    } //if
  } //for

  document.getElementsByName("txtTotalPrice")[0].value = totalprice;
}
<section id="checkCost">
  <h2>Total cost</h2>
  Total <input type="text" name="txtTotalPrice" size="10" value="-_-">
</section>

<span class="eventTitle">Winter</span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">Fam</span>
<span class="venueName">Disc</span>
<span class="eventPrice">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="12" data-price="0.00">


推荐阅读