gpt4 book ai didi

javascript - getTotal 函数不起作用

转载 作者:行者123 更新时间:2023-11-30 12:44:07 25 4
gpt4 key购买 nike

我正在尝试将以下伪代码转换为 javascript 函数(当通过其 title 属性选中复选框时计算价格):

function checkform(id) {
CREATE a variable called total set as zero;
GET a reference to the form into theForm;
GET a reference to all the input elements in theForm into array aInputElements;

FOR counter GOES FROM 1 TO aInputElements length
STORE a reference to aInputElements[ counter ] into currentElement;
IF currentElement is a checkbox AND currentElement is checked THEN
total ← total + currentElement.value;
ENDIF
ENDFOR
}

到目前为止我有这个:

function getTotal() {

// Get neccesary variables
var total = 0,
theForm = document.getElementById("bookingForm"),
inputs = theForm.getElementsByTagName("input"),
totalbox = document.getElementById("total");

// Add event listener for when any checkbox changes
for (var i = 0; i < inputs.length; i++) {

var currentElement = inputs[i];

if (currentElement.type == "checkbox") {
total = total + currentElement.title;
}

}

// Assign total to input
totalbox.value = total;

}

但是这不起作用并且正在添加:

“018.500.0013.0035.0016.0040.0015.0025.0016.0015.0027.5042.5020.0020.0020.000.000.0055.000.000.00”到 totalbox.value 当选中任何复选框时。

最佳答案

试试这个:

total = total + +currentElement.title;

或者简单地说:

total += +currentElement.title;

额外的 + 将强制将其读取为数字而不是字符串。


  • 显然,您也可以在标题上使用 parseFloat

关于javascript - getTotal 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23222769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com