将js变量插入表单变量
问题描述:
我想通过隐藏窗体将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的了解仅限于提出解决方案。
答
Total被定义为函数内的局部变量,因此不能在函数外的赋值中使用。
您可以在函数内部移动赋值,或让函数返回值。
答
变量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()
把最后一行的功能里面,或者有函数返回的结果,并直接分配给它 – thebreiflabb 2013-05-07 09:44:42
有无看看总的范围。这是一个只在函数calculate内有效的局部变量。 – 2013-05-07 09:45:52
我很尴尬,但非常感谢。 你绝对正确,@thebreiflabb。当然,其他人也一样。 如果你把它放在答案中,我会接受它... – dblaursen 2013-05-07 10:30:07