2013-05-07 99 views
0

我想通過隱藏窗體將js變量傳遞給php腳本。沒問題,通過它通過PHP,但我不能將變量放入窗體。將js變量插入表單變量

function calculate() {  
      var radio1 = document.forms["calcForm"].v1; 
      var radio2 = document.forms["calcForm"].v2; 

      var getf1 = getSelectedRadio(radio1); 
      var getf2 = getSelectedRadio(radio2); 

      var f1 = radio1[getf1].value; 
      var f2 = radio2[getf2].value; 

      var resultat = document.getElementById("resultat"); 
      var total = (parseInt(f1) + parseInt(f2)).toFixed(0); 
      resultat.value = total;//used to show value in another input-field 
      } 

document.contactForm.formTotal.value = total; 

這是導致我問題的最後一行,因爲它不會接受總數。函數計算完美無缺 - 當我用var x = 10等更簡單的變量替換total時,所有其他功能都能正常工作。

不知怎的,我想找到一種方法來將document.contactForm.formTotal.value設置爲total的值。

原因必須是它無法從函數中收回某些值 - 但是我對js的瞭解僅限於提出解決方案。

+0

把最後一行的功能裏面,或者有函數返回的結果,並直接分配給它 – thebreiflabb 2013-05-07 09:44:42

+0

有無看看總的範圍。這是一個只在函數calculate內有效的局部變量。 – 2013-05-07 09:45:52

+0

我很尷尬,但非常感謝。 你絕對正確,@thebreiflabb。當然,其他人也一樣。 如果你把它放在答案中,我會接受它... – dblaursen 2013-05-07 10:30:07

回答

0

Total被定義爲函數內的局部變量,因此不能在函數外的賦值中使用。

您可以在函數內部移動賦值,或讓函數返回值。

0

變量total超出了功能範圍。你可以聲明它的功能,但一個更好的辦法將是該函數返回一個值,例如:

function calculate() {  
     var radio1 = document.forms["calcForm"].v1; 
     var radio2 = document.forms["calcForm"].v2; 

     var getf1 = getSelectedRadio(radio1); 
     var getf2 = getSelectedRadio(radio2); 

     var f1 = radio1[getf1].value; 
     var f2 = radio2[getf2].value; 

     var resultat = document.getElementById("resultat"); 
     var total = (parseInt(f1) + parseInt(f2)).toFixed(0); 
     return resultat.value;//used to show value in another input-field 
     } 

var total = calculate()