2011-03-21 64 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