user3230289
user3230289

Reputation: 59

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.

Upvotes: 0

Views: 65

Answers (2)

Ashok Chitroda
Ashok Chitroda

Reputation: 361

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>

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

When var form = document.forms.myform is executed, there is no <form name="myform" ...yet.
The simplest (though maybe not the most sophisticated) solution is to move the <script> block from <head> to after the form code.

Upvotes: 1

Related Questions