Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Exclamation Help calculating a total!

    Hi everyone, my name is aaron and I'm working on a little project for fun. I'm nearly complete just have a few other things to finish up, this being one of the most important I thought I would start with this first. Basically I have a text box named "cost1" (goes up to 4) and need to multiply it by the quantity, "quantity1" in a drop down box and put it in the "total1" textbox. Here's what I have so far, but to no avail do I have it working, nor do I think I'm executing it properly. I was hoping to get it to run at the time the "cost" has changed and even the "quantity" one if too possible. Any help is much appreciated!

    PHP Code:
        <script type="text/javascript" language="JavaScript">
    function 
    calc_totals()
    {
        
    //gets values of field 1 and 2
        
    var c1 document.getElementById('cost1').value;
        var 
    q1 document.getElementById('quantity1').value;
        var 
    t1 document.getElementById('total1').value;
        var 
    c2 document.getElementById('cost2').value;
        var 
    q2 document.getElementById('quantity2').value;
        var 
    t2 document.getElementById('total2').value;
        var 
    c3 document.getElementById('cost3').value;
        var 
    q3 document.getElementById('quantity3').value;
        var 
    t3 document.getElementById('total3').value;
        var 
    c4 document.getElementById('cost4').value;
        var 
    q4 document.getElementById('quantity4').value;
        var 
    t4 document.getElementById('total4').value;
    if(
    c1 != null)
    {
    //does math on the values of field 1 and 2
      
    t1 c1 q1;
    //makes the value of outputfield = field1 + field2
      
    document.getElementById('total1').value t1;
    }
    if(
    c2 != null)
    {
    //does math on the values of field 1 and 2
      
    t2 c2 q2;
    //makes the value of outputfield = field1 + field2
      
    document.getElementById('total2').value t2;

    etc. etc, thank you!

  • #2
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    621
    Thanks
    0
    Thanked 6 Times in 6 Posts
    I want to give you as complete a solution as I possibly can. Here's a first example, just getting the code you have working:

    PHP Code:
    <html>

        <
    head>
            <
    style>
                
    body background:url(paper_fibers/paper_fibers.png); font-familyHelveticafont-size:14px;}
                
    #content { width: 500px; margin:3em auto; padding:20px;}
                
    table tr td:nth-child(3) { background-color:#00ffff;}
            
    </style>

            <
    script type="text/javascript" language="JavaScript">

                function 
    init() 
                {

                    var 
    calcButton document.getElementById('totals');

                    if (
    calcButton.addEventListener// this is to support real browsers ;)
                    
    {
                        
    calcButton.addEventListener("click",function() 
                        {
                            
    calc_totals();
                        }, 
    false);
                    } else if(
    calcButton.attachEvent) {    // this function is to support IE
                        
    calcButton.attachEvent("onclick",function()
                        {
                            
    calc_totals();
                        });
                    }

                }

                
    //=======================================================
                // Add our init function to the window load
                ////=======================================================
                
    if(window.addEventListener)     // non IE fail
                
    {
                    
    window.addEventListener("load"initfalse);
                } else if(
    window.attachEvent)     // IE fail
                
    {
                    
    window.attachEvent("onload"init);
                } else {
                   
    document.addEventListener("load"initfalse);
                }



                function 
    calc_totals() 
                { 
                    
    //gets values of field 1 and 2 
                    
    var c1 document.getElementById('cost1').value
                    var 
    q1 document.getElementById('quantity1'); 
                        
    q1 q1.options[q1.selectedIndex].value;
                    var 
    t1 document.getElementById('total1').value
                    var 
    c2 document.getElementById('cost2').value
                    var 
    q2 document.getElementById('quantity2');
                        
    q2 q2.options[q2.selectedIndex].value;
                    var 
    t2 document.getElementById('total2').value
                    var 
    c3 document.getElementById('cost3').value
                    var 
    q3 document.getElementById('quantity3');
                        
    q3 q3.options[q3.selectedIndex].value;
                    var 
    t3 document.getElementById('total3').value
                    var 
    c4 document.getElementById('cost4').value
                    var 
    q4 document.getElementById('quantity4'); 
                        
    q4 q4.options[q4.selectedIndex].value;
                    var 
    t4 document.getElementById('total4').value

                    if(
    c1 != null
                    { 
                    
    //does math on the values of field 1 and 2 
                      
    t1 c1 q1
                    
    //makes the value of outputfield = field1 + field2 
                      
    document.getElementById('total1').value t1
                    } 

                    if(
    c2 != null
                    { 
                    
    //does math on the values of field 1 and 2 
                      
    t2 c2 q2
                    
    //makes the value of outputfield = field1 + field2 
                      
    document.getElementById('total2').value t2
                    }
                }
            
    </script>

        </head>

        <body>
            <div id='content'>
                <form>
                <fieldset>
                    <legend>Totals</legend>

                    <table id='mytable'>
                        <thead>
                            <tr>
                                <th>Cost</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" id="cost1"></td>
                                <td><select id='quantity1'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total1'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost2"></td>
                                <td><select id='quantity2'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total2'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost3"></td>
                                <td><select id='quantity3'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total3'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost4"></td>
                                <td><select id='quantity4'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total4'></td>
                            </tr>
                            <tr>
                                <td colspan=3><input type='button' value='Get totals' id='totals'></td>
                            </tr>
                        </tbody>

                    </table>

                </fieldset>
                </form>
            </div>

        </body>

    </html> 

  • #3
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    621
    Thanks
    0
    Thanked 6 Times in 6 Posts
    The following version shows two different methods for determining which input values to get...and only works when the cost changes. The other thing I've done, is now you can have an infinite number of rows (not just 4), and the code will detect which fields it needs to update automatically.
    I'll post again when I've refactored it to use only Method 2, and works on changing either cost or Quantity.




    PHP Code:
    <!DOCTYPE html>
    <
    html>

        <
    head>
            <
    style>
                
    body background:url(paper_fibers/paper_fibers.png); font-familyHelveticafont-size:14px;}
                
    #content { width: 500px; margin:3em auto; padding:20px;}
                
    table tr td:nth-child(3) { background-color:#00ffff;}
            
    </style>

            <
    script type="text/javascript" language="JavaScript">

                function 
    init() 
                {

                    var 
    method 2;
                    var 
    calcButton document.getElementById('totals');    // for our click button event handler
                    
    var inputArray document.forms[0].getElementsByTagName('input');
                    var 
    selectArray document.forms[0].getElementsByTagName('select'), quantityArray;

                    
    // click button event handler
                    
    addEvent(calcButton,'click',function(ev
                    {
                        
    my_calc_totals();
                    });
            
                    
    // ---------------------------------------
                    //    Add event listeners
                    // ---------------------------------------

                    // loop through costs
                    
    for (var i=0i<inputArray.lengthi++)
                    {
                        if (
    inputArray[i].className !== 'cost') continue;    // wrong element, skip to next
                        
    var ele inputArray[i];
                        
                        
    // add the event handler
                        
    addEvent(ele,'change',function() 
                        {
                            
                            
    //======================================================================
                            // Now we need to get the current value, get the value of the right quantity,
                            // and figure out which box to put the total in.
                            // Then we run our get_sum() function and set the value
                            //======================================================================

                            
    var curCost this.value// the value of the current node

                            //======================================================================
                            // There are several ways to figure out what the right nodes are
                            // Method 1 : DOM Traversal
                            // Method 2 : based on ID
                            // Method 3 : we could add a custom attribute to each element via the
                            //              data- prefix. e.g. <select data-rowid='2' class='quantity'>
                            //              and then read that prefix.
                            //======================================================================

                            
    if (method == 1
                            {
                                
    // *********************************************************************
                                // Method 1 : DOM Traversal
                                // *********************************************************************

                                // ---------------------------------------
                                // I originally did this using the childNodes[x]
                                // where x was an index. While it worked with:
                                //        x = 1; // costs
                                //      x = 3; // quantity
                                //      x = 5; // totals
                                // I'm not sure about cross-browser compatibility
                                // As such, I switched to using the Resig functions
                                // ---------------------------------------
                        
                                // get parent <TD> of COSTS <TD>
                                
    var parentTD parent(this);
                                
                                
    // get quantity <TD>
                                
    var quantityTD next(parentTD);
                                
                                
    // get total <TD>
                                
    var totalTD next(quantityTD);

                                
    // get the Quantity value
                                
    var quantityArray quantityTD.getElementsByTagName('select');
                                var 
    curQuantity quantityArray[0];
                                
    curQuantity curQuantity.options[curQuantity.selectedIndex].value;

                                
    // get the Totals field
                                
    var totalsArray totalTD.getElementsByTagName('input');
                                var 
    totalInput totalsArray[0];
                                
                                
    // set the total
                                
    totalInput.value get_sum(curCost,curQuantity);

                            } else {
                                
                                
    // *********************************************************************
                                // Method 2 : based on ID
                                // *********************************************************************
                                
                                
    var idArray this.id.split('t'); // this splits the 'id' into an array
                                // our array looks like this:
                                // ['cost',<number>];
                                
                                
    var rowNum idArray[1]; // get the number 


                                // ---------------------------------------
                                // Now we know which elements to update
                                // ---------------------------------------
                                
    var curQuantity document.getElementById('quantity' rowNum).value;
                                var 
    totalInput  document.getElementById('total' rowNum);
                                
    totalInput.value get_sum(curCostcurQuantity);



                            }

                        });        
    // end event listener
                        

                    
    }    // end for loop


                
    }    // end init()

                //======================================================================
                // Add our init function to the window load
                //======================================================================

                // Cross-browser implementation of element.addEventListener()
                 // Example use:
                 //         var ele = document.getElementById('someElementID');
                 //        addEvent(ele,'click',function(ev) {
                 //            alert('ev');
                 //        });
                
    var addEventremoveEvent;
                
                if ( 
    window.addEventListener ) {
                  
    addEvent = function(objtypefn ) {
                    
    obj.addEventListener(typefnfalse );
                  }
                  
    removeEvent = function(objtypefn ) {
                  
    obj.removeEventListener(typefnfalse );
                  }
                } else if (
    document.attachEvent) {
                  
    addEvent = function(objtypefn ) {
                    var 
    eProp type fn;
                    
    obj['e'+eProp] = fn;
                    
    obj[eProp] = function(){obj['e'+eProp]( window.event );}
                    
    obj.attachEvent'on'+typeobj[eProp] );
                  }
                  
    removeEvent = function(objtypefn ) {
                    var 
    eProp type fn;
                    
    obj.detachEvent'on'+typeobj[eProp] );
                    
    obj[eProp] = null;
                    
    obj["e"+eProp] = null;
                  }
                }

                
    //======================================================================
                // Functions for dom Traversal; courtesy of John Resig
                //======================================================================
                
    function prevelem ) {
                    do {
                        
    elem elem.previousSibling;
                    } while ( 
    elem && elem.nodeType != );
                    return 
    elem;
                }
                function 
    nextelem ) {
                    do {
                        
    elem elem.nextSibling;
                    } while ( 
    elem && elem.nodeType != );
                    return 
    elem;
                }

                function 
    firstelem ) {
                    
    elem elem.firstChild;
                    return 
    elem && elem.nodeType != next elem ) : elem;
                }

                function 
    lastelem ) {
                    
    elem elem.lastChild;
                    return 
    elem && elem.NodeType != prev elem ) : elem;
                }
        
                function 
    parentelemnum ) {
                    
    num num || 1;
                    for ( var 
    0numi++ ) {
                        if ( 
    elem != null ) { elem elem.parentNode;}
                    }
                    return 
    elem;
                }


                
    // ---------------------------------------
                //   Run our init function on load
                // ---------------------------------------
                
    addEvent(window,'load',init);

                

                
    // ---------------------------------------
                // 
                // ---------------------------------------
                
    function my_calc_totals()
                {
                    
    // ---------------------------------------
                    //    Loop
                    // ---------------------------------------

                
    }

                function 
    get_sum(amountquantity)
                {
                    return 
    amount quantity;
                }

            
    </script>

        </head>

        <body>
            <div id='content'>
                <form>
                <fieldset>
                    <legend>Totals</legend>

                    <table id='mytable'>
                        <thead>
                            <tr>
                                <th>Cost</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" id="cost1" class='cost'></td>
                                <td><select id='quantity1' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total1'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost2" class='cost'></td>
                                <td><select id='quantity2' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total2'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost3" class='cost'></td>
                                <td><select id='quantity3' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total3'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost4" class='cost'></td>
                                <td><select id='quantity4' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total4'></td>
                            </tr>
                            <tr>
                                <td colspan=3><input type='button' value='Get totals' id='totals'></td>
                            </tr>
                        </tbody>

                    </table>

                </fieldset>
                </form>
            </div>

        </body>




    </html> 
    Last edited by Celtboy; 02-25-2013 at 07:02 AM.

  • #4
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    621
    Thanks
    0
    Thanked 6 Times in 6 Posts
    Ok. So this version is a little bit different. It uses a custom domready() function by Dustin Diaz to only bind events to the items when they've loaded.

    Additionally, I've changed the totals function into an object ( function RowUpdater() ), because this allows more flexibility in the callback.

    Lastly, this does require that the appropriate classes be assigned to each input, *AND* that the ID be: "cost_", "quantity_", "total_" and then the number.
    PHP Code:
    <!DOCTYPE html>
    <
    html>

        <
    head>
            <
    style>
                
    body background:url(paper_fibers/paper_fibers.png); font-familyHelveticafont-size:14px;}
                
    #content { width: 500px; margin:3em auto; padding:20px;}
                
    table tr td:nth-child(3) { background-color:#00ffff;}
            
    </style>

            <
    script>
            
    /*!
              * domready (c) Dustin Diaz 2012 - License MIT
              */
                
    !function(a,b){typeof module!="undefined"?module.exports=b():typeof define=="function"&&typeof define.amd=="object"?define(b):this[a]=b()}("domready",function(a){function m(a){l=1;while(a=b.shift())a()}var b=[],c,d=!1,e=document,f=e.documentElement,g=f.doScroll,h="DOMContentLoaded",i="addEventListener",j="onreadystatechange",k="readyState",l=/^loade|c/.test(e[k]);return e[i]&&e[i](h,c=function(){e.removeEventListener(h,c,d),m()},d),g&&e.attachEvent(j,c=function(){/^c/.test(e[k])&&(e.detachEvent(j,c),m())}),a=g?function(c){self!=top?l?c():b.push(c):function(){try{f.doScroll("left")}catch(b){return setTimeout(function(){a(c)},50)}c()}()}:function(a){l?a():b.push(a)}})

            
    </script>

            <script>

                function RowUpdater(ele) {

                    this.item = ele;


                    this.el = ele;
                    
                    var idArray = ele.id.split('_');
                    this.inpNum = idArray[1];
                    this.totalInput = document.getElementById('total_' + this.inpNum);

                    if (idArray[0] == 'cost') {
                        this.cost_el = ele;
                        this.quantity_el = document.getElementById('quantity_' + this.inpNum);
                    } else {
                        this.quantity_el = ele;
                        this.cost_el = document.getElementById('cost_' + this.inpNum);
                    }

                    var self = this;

                    this.get_sum = function(cost, quantity) {
                        return cost * quantity;
                    }

                    this.update = function() {

                        self.totalInput.value = self.get_sum(self.cost_el.value , self.quantity_el.options[self.quantity_el.selectedIndex].value);
                    }
                        
                }
                 domready(function() {

                    var inputArray = document.forms[0].getElementsByTagName('input');
                    var selectArray = document.forms[0].getElementsByTagName('select');
                
                    // loop through costs
                    for (var i=0; i<inputArray.length; i++)
                    {
                        if (inputArray[i].className !== 'cost') continue;    // wrong element, skip to next
                        var ele = inputArray[i];

                        var item = new RowUpdater(ele);
                        addEvent(ele,'change',item.update);
                        
                    }

                    // loop through quantities
                    for (var i=0; i<selectArray.length; i++)
                    {
                        if (selectArray[i].className !== 'quantity') continue;    // wrong element, skip to next
                        var ele = selectArray[i];
                        
                        var item = new RowUpdater(ele);
                        addEvent(ele,'change',item.update);
                        
                    }

                 });

                 var addEvent, removeEvent;
                
                if ( window.addEventListener ) {
                    addEvent = function(obj, type, fn ) {
                        obj.addEventListener(type, fn, false );
                    }
                    removeEvent = function(obj, type, fn ) {
                        obj.removeEventListener(type, fn, false );
                    }
                } else if (document.attachEvent) {
                      addEvent = function(obj, type, fn ) {
                        var eProp = type + fn;
                        obj['e'+eProp] = fn;
                        obj[eProp] = function(){obj['e'+eProp]( window.event );}
                        obj.attachEvent( 'on'+type, obj[eProp] );
                    }
                    removeEvent = function(obj, type, fn ) {
                        var eProp = type + fn;
                        obj.detachEvent( 'on'+type, obj[eProp] );
                        obj[eProp] = null;
                        obj["e"+eProp] = null;
                    }
                }

            </script>

        </head>

        <body>
            <div id='content'>
                <form>
                <fieldset>
                    <legend>Totals</legend>

                    <table id='mytable'>
                        <thead>
                            <tr>
                                <th>Cost</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" id="cost_1" class='cost'></td>
                                <td><select id='quantity_1' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_1'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_2" class='cost'></td>
                                <td><select id='quantity_2' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_2'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_3" class='cost'></td>
                                <td><select id='quantity_3' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_3'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_4" class='cost'></td>
                                <td><select id='quantity_4' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_4'></td>
                            </tr>
                        
                        </tbody>

                    </table>

                </fieldset>
                </form>
            </div>

        </body>
    </html> 
    Last edited by Celtboy; 02-25-2013 at 09:18 AM.

  • #5
    Regular Coder
    Join Date
    May 2002
    Location
    Virginia, USA
    Posts
    621
    Thanks
    0
    Thanked 6 Times in 6 Posts
    Lastly, here's a jQuery solution. It basically includes zero comments, and has the following requirements:
    - jQuery
    - costs have to have a class of 'cost'
    - quantities have a to have a class of 'quantity'
    - totals have to have a class of 'total'
    - cost, quantity, and total must all exist within the same parent <TR> (though this can be configured).

    It's much cleaner to maintain, but what you were proposing looked to be pure javascript, and it is infinitely more advisable that you learn how to do it with plain javascript before you learn how to do it with a library like jquery.

    PHP Code:
    <!DOCTYPE html>
    <
    html>

        <
    head>
            <
    style>
                
    body background:url(paper_fibers/paper_fibers.png); font-familyHelveticafont-size:14px;}
                
    #content { width: 500px; margin:3em auto; padding:20px;}
                
    table tr td:nth-child(3) { background-color:#00ffff;}
            
    </style>

            <!-- include 
    jQuery -->
            <
    script src="http://code.jquery.com/jquery-latest.min.js"></script>
            <script>
            $(function() {
                $('input.cost, select.quantity').on('change',function(ev) {

                    var row = $(this).parents('tr');

                    row.find('input.total').val( row.find('input.cost').val() * row.find('select.quantity').val() );

                });
            });
            </script>

        </head>

        <body>
            <div id='content'>
                <form>
                <fieldset>
                    <legend>Totals</legend>

                    <table id='mytable'>
                        <thead>
                            <tr>
                                <th>Cost</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" id="cost1" class='cost'></td>
                                <td><select id='quantity1' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total1' class='total'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost2" class='cost'></td>
                                <td><select id='quantity2' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total2' class='total'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost3" class='cost'></td>
                                <td><select id='quantity3' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total3' class='total'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost4" class='cost'></td>
                                <td><select id='quantity4' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total4' class='total'></td>
                            </tr>
                            <tr>
                                <td colspan=3><input type='button' value='Get totals' id='totals'></td>
                            </tr>
                        </tbody>

                    </table>

                </fieldset>
                </form>
            </div>
        </body>
    </html> 

  • #6
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Celtboy View Post
    Ok. So this version is a little bit different. It uses a custom domready() function by Dustin Diaz to only bind events to the items when they've loaded.

    Additionally, I've changed the totals function into an object ( function RowUpdater() ), because this allows more flexibility in the callback.

    Lastly, this does require that the appropriate classes be assigned to each input, *AND* that the ID be: "cost_", "quantity_", "total_" and then the number.
    PHP Code:
    <!DOCTYPE html>
    <
    html>

        <
    head>
            <
    style>
                
    body background:url(paper_fibers/paper_fibers.png); font-familyHelveticafont-size:14px;}
                
    #content { width: 500px; margin:3em auto; padding:20px;}
                
    table tr td:nth-child(3) { background-color:#00ffff;}
            
    </style>

            <
    script>
            
    /*!
              * domready (c) Dustin Diaz 2012 - License MIT
              */
                
    !function(a,b){typeof module!="undefined"?module.exports=b():typeof define=="function"&&typeof define.amd=="object"?define(b):this[a]=b()}("domready",function(a){function m(a){l=1;while(a=b.shift())a()}var b=[],c,d=!1,e=document,f=e.documentElement,g=f.doScroll,h="DOMContentLoaded",i="addEventListener",j="onreadystatechange",k="readyState",l=/^loade|c/.test(e[k]);return e[i]&&e[i](h,c=function(){e.removeEventListener(h,c,d),m()},d),g&&e.attachEvent(j,c=function(){/^c/.test(e[k])&&(e.detachEvent(j,c),m())}),a=g?function(c){self!=top?l?c():b.push(c):function(){try{f.doScroll("left")}catch(b){return setTimeout(function(){a(c)},50)}c()}()}:function(a){l?a():b.push(a)}})

            
    </script>

            <script>

                function RowUpdater(ele) {

                    this.item = ele;


                    this.el = ele;
                    
                    var idArray = ele.id.split('_');
                    this.inpNum = idArray[1];
                    this.totalInput = document.getElementById('total_' + this.inpNum);

                    if (idArray[0] == 'cost') {
                        this.cost_el = ele;
                        this.quantity_el = document.getElementById('quantity_' + this.inpNum);
                    } else {
                        this.quantity_el = ele;
                        this.cost_el = document.getElementById('cost_' + this.inpNum);
                    }

                    var self = this;

                    this.get_sum = function(cost, quantity) {
                        return cost * quantity;
                    }

                    this.update = function() {

                        self.totalInput.value = self.get_sum(self.cost_el.value , self.quantity_el.options[self.quantity_el.selectedIndex].value);
                    }
                        
                }
                 domready(function() {

                    var inputArray = document.forms[0].getElementsByTagName('input');
                    var selectArray = document.forms[0].getElementsByTagName('select');
                
                    // loop through costs
                    for (var i=0; i<inputArray.length; i++)
                    {
                        if (inputArray[i].className !== 'cost') continue;    // wrong element, skip to next
                        var ele = inputArray[i];

                        var item = new RowUpdater(ele);
                        addEvent(ele,'change',item.update);
                        
                    }

                    // loop through quantities
                    for (var i=0; i<selectArray.length; i++)
                    {
                        if (selectArray[i].className !== 'quantity') continue;    // wrong element, skip to next
                        var ele = selectArray[i];
                        
                        var item = new RowUpdater(ele);
                        addEvent(ele,'change',item.update);
                        
                    }

                 });

                 var addEvent, removeEvent;
                
                if ( window.addEventListener ) {
                    addEvent = function(obj, type, fn ) {
                        obj.addEventListener(type, fn, false );
                    }
                    removeEvent = function(obj, type, fn ) {
                        obj.removeEventListener(type, fn, false );
                    }
                } else if (document.attachEvent) {
                      addEvent = function(obj, type, fn ) {
                        var eProp = type + fn;
                        obj['e'+eProp] = fn;
                        obj[eProp] = function(){obj['e'+eProp]( window.event );}
                        obj.attachEvent( 'on'+type, obj[eProp] );
                    }
                    removeEvent = function(obj, type, fn ) {
                        var eProp = type + fn;
                        obj.detachEvent( 'on'+type, obj[eProp] );
                        obj[eProp] = null;
                        obj["e"+eProp] = null;
                    }
                }

            </script>

        </head>

        <body>
            <div id='content'>
                <form>
                <fieldset>
                    <legend>Totals</legend>

                    <table id='mytable'>
                        <thead>
                            <tr>
                                <th>Cost</th>
                                <th>Quantity</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><input type="text" id="cost_1" class='cost'></td>
                                <td><select id='quantity_1' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_1'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_2" class='cost'></td>
                                <td><select id='quantity_2' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_2'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_3" class='cost'></td>
                                <td><select id='quantity_3' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_3'></td>
                            </tr>
                            <tr>
                                <td><input type="text" id="cost_4" class='cost'></td>
                                <td><select id='quantity_4' class='quantity'>
                                    <option value='0'>0</option>
                                    <option value='10'>10</option>
                                    <option value='20'>20</option>
                                    <option value='50'>50</option>
                                </select>
                                </td>
                                <td><input type='text' id='total_4'></td>
                            </tr>
                        
                        </tbody>

                    </table>

                </fieldset>
                </form>
            </div>

        </body>
    </html> 
    Oh my lord, thank you so much you have been so helpful, I don't know how I can repay you. I was able to get it working and all. Thank you!

  • #7
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I have it full integrated and it looks great, only one thing though..
    53.910000000000004 is what I get for the input of 5.99 * 9, I just need to round it off and it would be perfect. I'll PM you the link

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,184
    Thanks
    80
    Thanked 4,451 Times in 4,416 Posts
    Code:
    var product = 5.99 * 9;
    document.getElementById("putItHere").value = product.toFixed(2);
    Or similar.

    toFixed( digitsRIghtOfDecimalPoint ) converts a number to a string with specified number of decimal digits. Note that the result *IS* a string, so you should *NOT* use it in further calculations. Only use it to present a "pretty" number to the user, as the last step in any processing.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    aaron1312 (02-27-2013)

  • #9
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    Code:
    var product = 5.99 * 9;
    document.getElementById("putItHere").value = product.toFixed(2);
    Or similar.

    toFixed( digitsRIghtOfDecimalPoint ) converts a number to a string with specified number of decimal digits. Note that the result *IS* a string, so you should *NOT* use it in further calculations. Only use it to present a "pretty" number to the user, as the last step in any processing.
    Thanks! I'll get to that part in a bit, but I just ran into a problem using the solution I quoted above. I'm using the POST command when sending it to the next page, I wasn't able to echo total_1

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,184
    Thanks
    80
    Thanked 4,451 Times in 4,416 Posts
    Form fields WITHOUT NAMES will *NEVER* be sent to the next page, whether using POST or GET.

    Putting an ID on a form field is *USELESS* for POST or GET purposes.

    If you think you need an ID (I don't think you do, but there's no point in rewriting that JS code at this point), okay. But then make sure you also give the field a name.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •