<html>

    <body>
    <form action="#" method="post">
            Addition 1:

        <input type="text" id="add1" name="add1" onkeyup="AutoCalc(this)" />      
        Subtraction 1:
        <input type="text" id="sub1" name="sub1" onkeyup="AutoCalc(this)" />  
        Addition 2:
        <input type="text" id="add2"  name="add1" onkeyup="AutoCalc(this)" />
        Subtraction 2:
        <input type="text" id="sub2" name="sub1" onkeyup="AutoCalc(this)" />      
        <label>
            Total</label>
        <input type="text" id="total" name="total" disabled="disabled" />
    </div>

    </body>
    </html>
<script>
    function AutoCalc(obj) {
           var total = 0;

           if (isNaN(obj.value)) {
               alert("Please enter a number :(");
               obj.value = '';
               return false;
           }
           else {

               var textBox = new Array();
               textBox = document.getElementsByTagName('input')

               for (i = 0; i < textBox.length; i++) {
                   if (textBox[i].type == 'text') {
                       var inputVal = textBox[i].value;
                       if (inputVal == '')
                           inputVal = 0;
                       if ((textBox[i].id == 'add1') || (textBox[i].id == 'add2')) {
                           total = total + parseInt(inputVal);
                       }

                       if ((textBox[i].id == 'sub1') || (textBox[i].id == 'sub2')) {
                           total = total - parseInt(inputVal);
                       }
                   }
               }
               document.getElementById('total').value = total;
           }
       }

       </script>

You should specify another php or HTML page for the action= component. In that page you can get the post variables and do the math... :-) If you construct your page properly, you can recursively call the same page. That said, just leaving the action out, the form will post to the same page, but you need to determine if you got post variables set, and then pass that data to the java script.

Edited 11 Months Ago by rubberman

This article has been dead for over six months. Start a new discussion instead.