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 6 of 6
  1. #1
    New Coder
    Join Date
    Dec 2012
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Need help on real-time calculation for array

    Hi,

    I have created a table with 3 column (A, B, C). When user enter value in column A & B, column C will auto-calculate the value from user input.

    By default, there will be 1 row and I am able to achieve the above auto-calculation. However, I create a Add button and when user click "Add", another row will shown with same column (A, B, C) but I am not able to achieve the auto-calculation.

    I have written the codes as below, can anyone please kindly help? Thanks.

    Code:
    <script type="text/javascript">
    
           function addInput(){
    	var tbl = document.getElementById('tblAddress');
    	var lastRow = tbl.rows.length;
    	var row = tbl.insertRow(lastRow);
    
    	var cell0 = row.insertCell(0);
                 var el = document.createElement('input');
    	el.type='text';
    	el.name='qty[]';
    	el.size='10';
    	cell0.appendChild(el);
    
    	var cell1 = row.insertCell(1);
                 var el = document.createElement('input');
    	el.type='text';
    	el.name='unitprice[]';
    	el.size='15';
    	cell1.appendChild(el);
    
    	var cell2 = row.insertCell(2);
                 var el = document.createElement('input');
    	el.type='text';
    	el.name='totalprice[]';
    	el.size='15';	
    	cell2.appendChild(el);
            }
    
    function getQuantity(){    
    	var theForm = document.forms["myform"];    
    	var quantity = theForm.elements["qty[]"];    
    	var howmany =0;    
    	 
    	if(quantity.value!=""){        
    		howmany = parseInt(quantity.value);    		
    	}
    	
    	return howmany;
    }
    
    function getUnitPrice(){    
    	var theForm = document.forms["myform"];    
    	var quantity = theForm.elements["unitprice[]"];    
    	var howmany =0;    
    	 
    	if(quantity.value!=""){        
    		howmany = parseFloat(quantity.value).toFixed(2);    		
    	}
    	
    	return howmany;
    }
    
    function getTotal(){
                var totalprice = getQuantity() * getUnitPrice();
    	document.getElementById('totalprice').value = totalprice.toFixed(2);
    }
    
    </script>
    
    <html>
    <body>
    <form name="form" id="myform">
    <table border="1" id="tblAddress">
           <tr>
    	<td><b>Qty<b></td>
    	<td><b>Unit Price<b></td>
    	<td><b>Total Price<b></td>
           </tr>
           <tr>
                <td><input type="text" name="qty[]" size="10" onkeyup="getTotal()"></td>
    	<td><input type="text" name="unitprice[]" size="15" onkeyup="getTotal()"></td>
    	<td><input type="text" name="totalprice[]" size="15" id="totalprice"></td>
           </tr>
    </table>
    <input type="button" value="Add" onClick="addInput();"><br><br>
    </form>
    </body>
    </html>

  • #2
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    Code:
    <html>
    <body>
    <script type="text/javascript">
    
    function addInput(){
      var tbl = document.getElementById('tblAddress');
      var lastRow = tbl.rows.length;
      var row = tbl.rows[lastRow-1].cloneNode(true);
      tbl.tBodies[0].appendChild(row);
      var txts = row.getElementsByTagName('input');
      for(var i = 0; i < txts.length; i++) {
        if(txts[i].type == 'text') {
          txts[i].value = '';
        }
      }
    }
    
    function getTotal(){
      var quantity = document.getElementsByName("qty[]");
      var unitprice = document.getElementsByName("unitprice[]");
      var totalprice = document.getElementsByName("totalprice[]");
      for(var i = 0; i < quantity.length; i++) {
        totalprice[i].value = (quantity[i].value * unitprice[i].value).toFixed(2)
      }
    }
    
    </script>
    <form name="form" id="myform">
      <table border="1" id="tblAddress">
      <tr>
        <td><b>Qty<b></td>
        <td><b>Unit Price<b></td>
        <td><b>Total Price<b></td>
      </tr>
      <tr>
        <td><input type="text" name="qty[]" size="10" onkeyup="getTotal()"></td>
        <td><input type="text" name="unitprice[]" size="15" onkeyup="getTotal()"></td>
        <td><input type="text" name="totalprice[]" size="15" id="totalprice"></td>
      </tr>
      </table>
      <input type="button" value="Add" onClick="addInput();"><br><br>
    </form>
    </body>
    </html>

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    I have taken the liberty of augmenting/improving niralsoni's code a little for practical usage (such as blocking NaN, calculating/displaying a grand total, allowing decimal values of prices etc.):-

    Code:
    <html>
    <body>
    <script type="text/javascript">
    
    function addInput() {
    
    var tbl = document.getElementById('tblAddress');
    var lastRow = tbl.rows.length;
    var row = tbl.rows[lastRow-1].cloneNode(true);
    tbl.tBodies[0].appendChild(row);
    var txts = row.getElementsByTagName('input');
    for(var i = 0; i < txts.length; i++) {
    if(txts[i].type == "text") {
    txts[i].value = "";
    }
    }
    
    }
    
    function getTotal() {
    
    var grandtotal =0;
    var quantity = document.getElementsByName("qty[]");
    var unitprice = document.getElementsByName("unitprice[]");
    var totalprice = document.getElementsByName("totalprice[]");
    
    for(var i = 0; i < quantity.length; i++) {
    var q = Math.abs(Number(quantity[i].value)) || 0;  // block NaN entries or negative values
    q = Math.floor(q);  // make integer
    quantity[i].value = q;  // write it back to the field
    var up = Math.abs(Number(unitprice[i].value)) || 0;
    up = up.toFixed(2);  // for display
    if (up != 0) {unitprice[i].value = up;}
    else {unitprice[i].value = "";}  // blank out 0 price
    up = Number(up);  // back to a number;
    
    var itemprice = q * up;
    grandtotal += itemprice;
    totalprice[i].value = itemprice.toFixed(2);
    document.getElementById("grdtot").value = grandtotal.toFixed(2);
    }
    
    }
    
    </script>
    
    <form id="myform">
      <table border="1" id="tblAddress">
      <tr>
        <td><strong>Description</strong></td>
        <td><strong>Qty</strong></td>
        <td><strong>Unit Price</strong></td>
        <td><strong>Total Price</strong></td>
      </tr>
      <tr>
        <td><input type="text" name="desc[]" size="40"></td>
        <td><input type="text" name="qty[]" size="4" onblur="getTotal()"></td>
        <td><input type="text" name="unitprice[]" size="12" onblur="getTotal()"></td>
        <td><input type="text" name="totalprice[]" size="12" id="totalprice" readonly></td>
      </tr>
      </table>
      <input type="button" value="Add" onClick="addInput();">
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong>Grand Total </strong><input type = "text" id = "grdtot" size = "12" readonly>
    </form>
    </body>
    </html>

    Quizmaster: In seafood on a restaurant menu, the French word "poisson" translates into English as what?
    Contestant: Chicken
    Last edited by Philip M; 02-15-2013 at 03:18 PM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    jmrker (02-15-2013)

  • #4
    New Coder
    Join Date
    Dec 2012
    Posts
    22
    Thanks
    1
    Thanked 0 Times in 0 Posts
    niralsoni & Philip, thanks for the help.

    Based on the code, I have some questions that I don't understand, can kindly advice? Thanks.

    1. The codes in addInput, can kindly explain what actually each line means? Not very good in js but I tried to put the comments, not sure is it what I understand.

    Code:
    function addInput() {
    
    var tbl = document.getElementById('tblAddress'); //Get the id of the table
    var lastRow = tbl.rows.length; //Number of current rows
    var row = tbl.rows[lastRow-1].cloneNode(true); //Clone the previous row
    tbl.tBodies[0].appendChild(row); //????
    var txts = row.getElementsByTagName('input'); //Get all the tag name with input
    //For each row, set the value of each textbox to empty 
    for(var i = 0; i < txts.length; i++) {
    if(txts[i].type == "text") {
    txts[i].value = "";
    }
    }
    
    }
    2. When user click add button, a new row will appear and there will be a remove button inside the last column beside totalprice textbox.

    I have the Remove function but I am not sure how to append inside the new addInput function.

    Below code is my previous addInput function:
    Code:
    	var cell6 = row.insertCell(6);
            var el = document.createElement('input');
    	el.type='text';
    	el.name='totalprice[]';
    	el.size='15';	
    	cell6.appendChild(el);
    	  	  
      	el = document.createElement('input');
      	el.type ='button';
      	el.value='Remove';
      	el.onmouseup=function(){ Remove(this); }
     	cell6.appendChild(el);
    Code:
    function Remove(obj){
     while (obj.parentNode){
      if (obj.nodeName.toUpperCase()=='TR'){
       break;
      }
      obj=obj.parentNode;
     }
     obj.parentNode.removeChild(obj);
     return;
    }
    3. After getting the grandtotal, I have another 3 fields but I am not able to get point b and c results, those highlighted in red are the codes that I added:
    a) GST -> using grandtotal * 0.07 (I am able to get this)
    b) Handling fees -> user will have to input a fee in the textbox
    c) Total -> This will be the grandtotal + GST + handling fees

    Code:
    <html>
    <body>
    <script type="text/javascript">
    
    function addInput() {
    
    var tbl = document.getElementById('tblAddress');
    var lastRow = tbl.rows.length;
    var row = tbl.rows[lastRow-1].cloneNode(true);
    tbl.tBodies[0].appendChild(row);
    var txts = row.getElementsByTagName('input');
    for(var i = 0; i < txts.length; i++) {
    if(txts[i].type == "text") {
    txts[i].value = "";
    }
    }
    
    }
    
    function getTotal() {
    
    var grandtotal =0;
    var gst = 0;
    var total = 0;
    var quantity = document.getElementsByName("qty[]");
    var unitprice = document.getElementsByName("unitprice[]");
    var totalprice = document.getElementsByName("totalprice[]");
    var handling = document.getElementsByName("handling");
    	
    var h = Math.abs(Number(handling.value)) || 0;
    h = h.toFixed(2);
    handling.value = h;
    
    for(var i = 0; i < quantity.length; i++) {
    var q = Math.abs(Number(quantity[i].value)) || 0;  // block NaN entries or negative values
    q = Math.floor(q);  // make integer
    quantity[i].value = q;  // write it back to the field
    var up = Math.abs(Number(unitprice[i].value)) || 0;
    up = up.toFixed(2);  // for display
    if (up != 0) {unitprice[i].value = up;}
    else {unitprice[i].value = "";}  // blank out 0 price
    up = Number(up);  // back to a number;
    
    var itemprice = q * up;
    grandtotal += itemprice;
    gst = grandtotal * 0.07;
    total = gst + grandtotal + h;
    
    totalprice[i].value = itemprice.toFixed(2);
    document.getElementById("grdtot").value = grandtotal.toFixed(2);
    document.getElementById("gst").value = gst.toFixed(2);
    document.getElementById("total").value = total.toFixed(2);
    }
    
    }
    
    </script>
    
    <form id="myform">
      <table border="1" id="tblAddress">
      <tr>
        <td><strong>Description</strong></td>
        <td><strong>Qty</strong></td>
        <td><strong>Unit Price</strong></td>
        <td><strong>Total Price</strong></td>
      </tr>
      <tr>
        <td><input type="text" name="desc[]" size="40"></td>
        <td><input type="text" name="qty[]" size="4" onblur="getTotal()"></td>
        <td><input type="text" name="unitprice[]" size="12" onblur="getTotal()"></td>
        <td><input type="text" name="totalprice[]" size="12" id="totalprice" readonly></td>
      </tr>
      </table>
      <input type="button" value="Add" onClick="addInput();">
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong>Grand Total </strong><input type = "text" id = "grdtot" size = "12" readonly><br>
    <strong>GST </strong><input type = "text" id = "gst" size = "12" readonly><br>
    <strong>Handling Fee </strong><input type = "text" name = "handling" size = "12" onblur="getTotal()"><br>
    <strong>Total </strong><input type = "text" id = "total" size = "12" readonly><br>
    
    
    </form>
    </body>
    </html>

  • #5
    Regular Coder
    Join Date
    Mar 2008
    Location
    London
    Posts
    152
    Thanks
    4
    Thanked 42 Times in 42 Posts
    Code:
    <html>
    <body>
    <script type="text/javascript">
    
    function addInput() {
      // get reference to the existing table object
      var tbl = document.getElementById('tblAddress');
      // get total number of rows 
      var lastRow = tbl.rows.length;
      // clone the last row (i.e. create a copy of last row added
      // the parameter "true" indicates recursive cloning of all the
      // child nodes. Setting it to false will simply create the 
      // copy of row object only.
      var row = tbl.rows[lastRow-1].cloneNode(true);
      // once new row is created, append it to the existing table
      tbl.tBodies[0].appendChild(row);
      // get all the input elements within the newly created row
      var txts = row.getElementsByTagName('input');
      // for each input type=text, clean the contents
      // you can also add more rules here to set the default values
      // whenever a new row is added.
      // also, if your row has multiple controls - textarea, checkbox,
      // dropdown boxes etc.. you need to handle them separately
      for(var i = 0; i < txts.length; i++) {
        if(txts[i].type == "text") {
          txts[i].value = "";
        }
      }
    }
    
    function getParent(obj, parentType) {
      while (obj.parentNode){
        if (obj.nodeName.toUpperCase()==parentType) {
          break;
        }
        obj=obj.parentNode;
      }
      return obj;
    }
    
    function removeInput(obj){
      var row = getParent(obj, 'TR');
      var tbl = getParent(row, 'TABLE');
      if(tbl.rows.length > 2) { // one header row and one mandatory data row
        // every row has a rowIndex attribute attached
        // simply call the inbuilt deleteRow method by passing the row index
        tbl.deleteRow(row.rowIndex);
        // recalculate post deletion
        getTotal();
      }
    }
    
    function getTotal() {
      var grandtotal =0;
      var quantity = document.getElementsByName("qty[]");
      var unitprice = document.getElementsByName("unitprice[]");
      var totalprice = document.getElementsByName("totalprice[]");
      var handling = document.getElementById("handling");
        
      var h = Math.abs(Number(handling.value)) || 0;
    
      for(var i = 0; i < quantity.length; i++) {
        var q = Math.abs(Number(quantity[i].value)) || 0;  // block NaN entries or negative values
        q = Math.floor(q);  // make integer
        quantity[i].value = q;  // write it back to the field
        var up = Math.abs(Number(unitprice[i].value)) || 0;
        up = up.toFixed(2);  // for display
        if (up != 0) {unitprice[i].value = up;}
        else {unitprice[i].value = "";}  // blank out 0 price
        up = Number(up);  // back to a number;
    
        var itemprice = q * up;
        grandtotal += itemprice;
        totalprice[i].value = itemprice.toFixed(2);
      }
      var gst = parseFloat(grandtotal * 0.07);
      var total = gst + grandtotal + h;
      h = h.toFixed(2);
      handling.value = h;
      document.getElementById("grdtot").value = grandtotal.toFixed(2);
      document.getElementById("gst").value = parseFloat(gst).toFixed(2);
      document.getElementById("total").value = parseFloat(total).toFixed(2);
    }
    
    </script>
    
    <form id="myform">
      <table border="1" id="tblAddress">
      <tr>
        <td><strong>Description</strong></td>
        <td><strong>Qty</strong></td>
        <td><strong>Unit Price</strong></td>
        <td><strong>Total Price</strong></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td><input type="text" name="desc[]" size="40"></td>
        <td><input type="text" name="qty[]" size="4" onblur="getTotal()"></td>
        <td><input type="text" name="unitprice[]" size="12" onblur="getTotal()"></td>
        <td><input type="text" name="totalprice[]" size="12" readonly></td>
        <td><input type="button" value="Remove" onclick="removeInput(this)"></td>
      </tr>
      </table>
      <input type="button" value="Add" onClick="addInput();">
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong>Grand Total </strong><input type = "text" id = "grdtot" size = "12" readonly><br>
    <strong>GST </strong><input type = "text" id = "gst" size = "12" readonly><br>
    <strong>Handling Fee </strong><input type = "text" id = "handling" size = "12" onblur="getTotal()"><br>
    <strong>Total </strong><input type = "text" id = "total" size = "12" readonly><br>
    </form>
    </body>
    </html>

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    I don't know about Australian GST, but in the UK the handling fee would be subject to VAT as well. Just a detail. Easily modified to suit.


    Code:
    var VAT = parseFloat((grandtotal +  hdlg) * 0.20);  // VAT is payable on handing charge
    var total = VAT + hdlg + grandtotal;
    hdlg = hdlg.toFixed(2);
    document.getElementById("handling").value = hdlg;

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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