表单文本框不会自动更新

时间:2012-09-02 00:49:37

标签: javascript

这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>The Raptor Astronomer</title>
        <script>
          function getQuantity()
{
    var theForm = document.forms["formula"];
    var radiusform = theForm.elements["radius"];
    var radius =0;
    if(radiusform.value!="")
    {
        radius = parseInt(radiusform.value);
          var circumference = radius * 2 * Math.PI;
    }
theForm.elements["circumference"].value = var circumference;
}
getQuantity();

    </script>
    </head>
    <body>
        <form id="formula">
            <label>Radius</label>
            <input id="radius" name="radius" type="text" />
            <label>Circumference</label>
            <input id="circumference" name="circumference" type="text"/>
        </form>

    </body>
</html>

据我从教程中可以看出,我的代码应该更新为圆周 - 虽然我没有看到这种情况。

为什么这不能正常运行?我不包括触发器吗?是否需要触发?

2 个答案:

答案 0 :(得分:0)

删除var: -

theForm.elements["circumference"].value = circumference;

并在if

之前声明
var circumference=0
if(radiusform.value!="")
    {
        radius = parseInt(radiusform.value);
        circumference = radius * 2 * Math.PI;
    }

答案 1 :(得分:0)

做了一些小改动。请参阅 jsFiddle example 。我将调用脚本绑定到radius输入元素的onchange事件。你也不能使用var作为作业的一部分,所以我把它移到了正确的位置。

<强>的JavaScript

function getQuantity() {
    var theForm = document.forms["formula"];
    var radiusform = theForm.elements["radius"];
    var radius = 0;
    var circumference;
    if (radiusform.value != "") {
        radius = parseInt(radiusform.value);
        circumference = radius * 2 * Math.PI;
    }
    theForm.elements["circumference"].value = circumference;
}

<强> HTML

 <form id="formula">
            <label>Radius</label>
            <input id="radius" name="radius" type="text" onChange="getQuantity()"/>
            <label>Circumference</label>
            <input id="circumference" name="circumference" type="text"/>
        </form>​