我有下面的代码检查我动态生成的offhire box,看看是否有提交的整数值。如果我要检查最后一个数组的总和,看看所有加在一起的方框是否大于0,我将如何实现。
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
//alert("You entered: " + pro[i].value)
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
}
return true;
}
非常感谢您的帮助
史蒂夫
答案 0 :(得分:1)
通过在循环中添加累加器来更改代码,然后检查循环外的累加器:
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var accumulator = 0;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
else{
accumulator += parseInt(offhire2);
}
}
if(accumulator > 0){
return true;
}
}
答案 1 :(得分:0)
您正在保存数组中的所有值。所以你可以使用循环来添加所有值。
var totalValue = 0;
var i=0;
while(offhire1[i])
{
totalValue += offhire1[i] ;
i++
}
if(totalValue)
{
// Non zero
}
如果我错了,你能不能更具体。
答案 2 :(得分:-1)
你必须:
forEach
功能将值一起添加。像:
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]*$/;
var num2 = num1.value;
var i=0;
var offhire1 = [];
for(var i = 0; i < num2; i++) {
offhire1[i] = parseFloat(document.getElementById('offhire1' + i));
var offhire2 = offhire1[i].value;
//if(nameRegex.match(pro[i].value)){
if(!offhire2.match(test2Regex)){
//alert("You entered: " + pro[i].value)
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
}
var sum = 0;
offhire1.forEach(function(a) {sum+=a});
// here, sum is the sum of offhire1's values
return true;
}