2011-03-21 68 views
0

我有下面的代码,它检查我动态生成的offhire盒子,看看是否有一个整数值出现onsubmit。如果我在最后检查数组的总和,看看所有加在一起的盒子是否都大于0,我会如何实现这一点。比较javascript数组与结果

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; 
} 

非常感谢您的帮助

史蒂夫

回答

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; 
    } 
} 
+0

谢谢。这是什么之后;) – 2011-03-21 07:07:36

-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; 
} 
+0

我不会考虑forEach安全的跨浏览器兼容性。 – Kevin 2011-03-21 06:47:46

+0

感谢您的输入 – 2011-03-21 07:08:27

0

要保存在阵列中的所有值。所以你可以使用循环加起来所有的值。

var totalValue = 0; 
var i=0; 
while(offhire1[i]) 
{ 
totalValue += offhire1[i] ; 
i++ 
} 
if(totalValue) 
{ 
// Non zero 
} 

请问你是否更具体,如果我错了。

+0

'totalValue'是truthy负值,但。我真的会检查'> 0'。 – pimvdb 2011-03-21 06:51:22

+0

我已经这样说了,因为问题是检查它是否大于零。 – Prakashm88 2011-03-21 06:53:40

+0

感谢您的帮助 – 2011-03-21 07:08:08