简体   繁体   English

使用JavaScript自动计算

[英]Auto calculation using javascript

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            var form = document.forms.myform,
                    qty = form.qty,
                    cost = form.cost,
                    output = form.textbox;

            window.calculate = function () {
                var q = parseInt(qty.value, 10) || 0,
                        c = parseFloat(cost.value) || 0;
                output.value = (q * c).toFixed(2);
            };
        </script>

    </head>
    <body>
        <form action="caltest.php" method="post" name="myform" onkeyup="calculate()">
            <label>Num of PAX :</label>
            <input type="text" name="qty" />
            <input type="hidden" name="cost" value="700" />
            <br/>
            <lable>Total Price: </lable>
            <input type="text" name="textbox" />

        </form>
    </body>
</html>

I am doing a simple calculation.Not getting any output. 我正在做一个简单的计算。没有得到任何输出。

When var form = document.forms.myform is executed, there is no <form name="myform" ...yet. 当执行var form = document.forms.myform ,还没有<form name="myform" ...。
The simplest (though maybe not the most sophisticated) solution is to move the <script> block from <head> to after the form code. 最简单的(尽管可能不是最复杂的)的解决方案是在移动<script>从块<head>的形式的代码之后

Try this one is working 试试这个一个工作

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>

    </head>
    <body>
        <form action="caltest.php" method="post" name="myform" onkeyup="calculate()" >
            <label>Num of PAX :</label>
            <input type="text" name="qty" />
            <input type="hidden" name="cost" value="700" />
            <br/>
            <lable>Total Price: </lable>
            <input type="text" name="textbox" />
      </form>    
      <script>
            var form = document.forms.myform,
                    qty = form.qty,
                    cost = form.cost,
                    output = form.textbox;

            window.calculate = function () {
                var q = parseInt(qty.value, 10) || 0,
                        c = parseFloat(cost.value) || 0;
                output.value = (q * c).toFixed(2);
            };
        </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM