javascript - 用于从表单中添加复选框的 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">
解决方案
有一些涉及案例的错误。
你使用form.getElementById
而不是document.getElementById
与form.querySelectorAll
而不是相同document.querySelectorAll
另外,您正在使用getElementsByName
which 返回一个数组,因此仅返回 [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">
推荐阅读
- jasper-reports - 如何更正此 Jasper,以便文本字段拉伸其高度以显示字符串的所有 500 个字符
- python - psycopg2 使用动态 WHERE 批量更新 execute_values
- ios - 在 iOS 应用程序中找不到 .dylib 的路径
- excel - 从 Word 到 Excel 的多级列表
- asp.net-mvc - HtmlHelper 不包含单个表单的 BeginForm 定义
- flutter - Flutter 访问我从 NavigationService 传递的值
- sql - 转置表更改日志格式以显示最大和最小日期
- javascript - 从 Google 表格导入数据
- android - 如果 android:sharedUserId 更改,我如何保持系统应用程序的用户先前数据完好无损?
- ios - 如何更改要在 Swift 中共享的文件的默认名称?