我正在尝试将以下伪代码转换为javascript函数(当按标题属性选择复选框时计算价格):
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.0015.0027.5042.5020.0020.0020.000.000.0055.000.000.00”到totalbox.value。
答案 0 :(得分:2)
试试这个:
total = total + +currentElement.title;
或者简单地说:
total += +currentElement.title;
额外的+
将强制它被读取为数字而不是字符串。
parseFloat
。答案 1 :(得分:1)
您的实施存在一些缺陷。
1)要匹配您的伪代码,您需要确认该复选框实际上是已选中:
if (currentElement.type == "checkbox" && currentElement.checked)
2)JavaScript +
运算符不仅用于添加数字,还用于连接字符串。为避免意外行为,您必须先解析输入(在本例中为包含数字的复选框标题)。有三种解决方案可以做到:
// Explicit conversion into a number (as a float)
total = total + +currentElement.title;
// Parse into a number (as a float)
total = total + parseFloat(currentElement.title);
// Parse into a number (as an integer)
total = total + parseInt(currentElement.title);
3)在更通用的域中的最后建议,最好使用HTML5 Custom Data Attribute将数据存储到HTML元素中。在你的情况下:
<!-- HTML code -->
<input type="checkbox" id="stackoverflow" data-total="12.34">
// JS code
var element = document.getElementById('stackoverflow');
var dataAsString = element.getAttribute('data-total');
var dataAsNumber = parseFloat(dataAsString);
答案 2 :(得分:0)
尝试解析浮动,如下所示。
total = parseFloat(total) + parseFloat(currentElement.title);