Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-15-2013, 09:26 AM   PM User | #1
holy24
New Coder

 
Join Date: Dec 2012
Posts: 20
Thanks: 1
Thanked 0 Times in 0 Posts
holy24 is an unknown quantity at this point
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>
holy24 is offline   Reply With Quote
Old 02-15-2013, 10:46 AM   PM User | #2
niralsoni
Regular Coder

 
Join Date: Mar 2008
Location: London
Posts: 143
Thanks: 3
Thanked 38 Times in 38 Posts
niralsoni is an unknown quantity at this point
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>
niralsoni is offline   Reply With Quote
Old 02-15-2013, 01:39 PM   PM User | #3
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,100
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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
__________________

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.

Last edited by Philip M; 02-15-2013 at 02:18 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
jmrker (02-15-2013)
Old 02-18-2013, 05:23 AM   PM User | #4
holy24
New Coder

 
Join Date: Dec 2012
Posts: 20
Thanks: 1
Thanked 0 Times in 0 Posts
holy24 is an unknown quantity at this point
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>
holy24 is offline   Reply With Quote
Old 02-18-2013, 10:43 AM   PM User | #5
niralsoni
Regular Coder

 
Join Date: Mar 2008
Location: London
Posts: 143
Thanks: 3
Thanked 38 Times in 38 Posts
niralsoni is an unknown quantity at this point
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>
niralsoni is offline   Reply With Quote
Old 02-18-2013, 12:09 PM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,100
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
Philip M is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:49 AM.


Advertisement
Log in to turn off these ads.