变量不更新

时间:2011-05-24 08:33:22

标签: javascript html

我有2个文件,我的索引和我的JS文件。

在我的索引中,我将有一个输入字段的形式,我的索引文件将链接到我的JS文件。

在我的JS文件中,我将有一个变量列表,这些变量将从我的索引文件input字段中获取它们的值。我计划在函数中将我的一些值相乘。

在不返回NaNundefined的情况下,执行此操作的正确方法是什么?

我一直试图通过设置onkeyup或onclick上的var值作为'document.getelementbyid',但它永远不会返回任何内容......

一些示例代码是, HTML

<input type="radio" id="ServiceLevel" value="0.84" name="ServiceLevel"onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.67" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.56" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.28" name="ServiceLevel" onclick="getValue()"/>
<input type="radio" id="ServiceLevel" value="0.14" name="ServiceLevel" onclick="getValue()"/>

和JS

var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;

// Cost Estimate
var CostEstimate = ServiceLevel * EstimatedCoreHours;

function CalculateEstimate() {  

alert('test = ' +CostEstimate);

// Estimate Cost
parseInt(document.getElementById("PriceEstimate").innerHTML=CostEstimate.toFixed(2));

// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").innerHTML=EstimatedCoreHours.toFixed(2));

}

3 个答案:

答案 0 :(得分:0)

我试过这个检查:

var ServiceLevel = document.getElementById(ServiceLevel).value;
var EstimatedCoreHours = 10;

 // Cost Estimate
CostEstimate = ServiceLevel * EstimatedCoreHours;

function CalculateEstimate() {  

alert('test = ' +CostEstimate);

// Estimate Cost
parseInt(document.getElementById("PriceEstimate").value=CostEstimate.toFixed(2));

// Estimate Core Hours
parseInt(document.getElementById("EstimatedCoreHours").value=EstimatedCoreHours.toFixed(2));

}

答案 1 :(得分:0)

您需要在javascript中获取值。这是你应该怎么做

创建文件index.htm

<html>
<head>
<script src="script.js"></script>
</head>
<body>

<form>
<input id="a1" name="a1">
<input id="a2" name="a2">
<input id="a3" name="a3">
<input type=button onClick='Calculate()'>
</form>
</body>
</html>

<强>的script.js

function Calculate()
{
   var v1 = document.getElementById ("a1").value;
   var v2 = document.getElementById ("a2").value;
   var v3 = document.getElementById ("a3").value;
  var total =  GetNumeric (v1) + GetNumeric(v2) + GetNumeric(v3);
}


function GetNumeric(val) {

    if (isNaN(parseFloat(val))) {

          return 0;
     }

     return parseFloat(val);

}

答案 2 :(得分:0)

  1. 首先是
  2. var ServiceLevel = document.getElementById(ServiceLevel).value;

    // ServiceLevel = null

    这应该在函数中,而在打开此网页时,getElementById将为null。

    2 。您的输入单选按钮具有相同的名称和ID,如果是这种情况应该采取值,或者他们是个人OR组

相关问题