473,387 Members | 1,757 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to calculate a total from a list of cells

Can anyone help, I am try to create a simple form using a table, where a
user can fill out
quanty and price and have a total automatically calculated and inserted in
another field.
I stuck trying to figure out how expand this script to recalculate when rows
are added or
removed.
My code so far.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>Testing Tables Calculation</title>
<script language="JavaScript" src="/javascript/testtables.js"></script>
</head>
<body>
<form name="myform" method="post" action="">
<table id="itemlist" cellspacing="2" cellpadding="2" border="1">
<tr>
<th>Qty</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="text" name="qty1" size="7" onChange="calc_total()"
maxlength="7">&nbsp;</td>
<td><input type="text" name="cost1" size="7" onChange="calc_total()"
maxlength="7">&nbsp;</td>
</tr>
</table>
<hr>
<table id="totalcost" border="1">
<tr>
<td><input type="text" size="7" name="test" readonly>&nbsp;</td>
<td><input type "text" size="7" name="total" readOnly>&nbsp;</td>
</tr>
</table>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
</form>
</body>
</html>

<!-- Begin Add Row to Itemlist Table
function addRowToTable()
{
lastRow=1;
var tbl = document.getElementById('itemlist');
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

// qty cell
var qty = row.insertCell(0);
var el_qty = document.createElement('input');
el_qty.setAttribute('type', 'text');
el_qty.setAttribute('name', 'qty' + iteration);
el_qty.setAttribute('size', '7');
el_qty.setAttribute('maxlength', '7');
el_qty.setAttribute('onChange', 'calc_total()');
qty.appendChild(el_qty);

// price cell
var price = row.insertCell(1);
var el_price = document.createElement('input');
el_price.setAttribute('type', 'text');
el_price.setAttribute('name', 'price' + iteration);
el_price.setAttribute('size', '7');
el_price.setAttribute('maxlength', '4');
el_price.setAttribute('onChange', 'calc_total()');
price.appendChild(el_price);
}

//Remove a row from the table
function removeRowFromTable()
{
var tbl = document.getElementById('itemlist');
var last_Row = tbl.rows.length;
if (last_Row > 2) tbl.deleteRow(last_Row - 1);
}

// Calculate the total
function calc_total()
{
var num_of_units = document.myform.qty1.value;
var price_of_units = document.myform.cost1.value;
var total_cost = eval(num_of_units * price_of_units)
document.myform.total.value = total_cost;
}
//-->
Jul 23 '05 #1
7 2810
In article
<mW*********************@twister01.bloor.is.net.ca ble.rogers.com>, rick
<rmsingh@no_spam_rogers.com> wrote:
Can anyone help, I am try to create a simple form using a table, where a
user can fill out
quanty and price and have a total automatically calculated and inserted in
another field.
I stuck trying to figure out how expand this script to recalculate when rows
are added or
removed.
My code so far.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title>Testing Tables Calculation</title>
<script language="JavaScript" src="/javascript/testtables.js"></script>
</head>
<body>
<form name="myform" method="post" action="">
<table id="itemlist" cellspacing="2" cellpadding="2" border="1">
<tr>
<th>Qty</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="text" name="qty1" size="7" onChange="calc_total()"
maxlength="7">&nbsp;</td>
<td><input type="text" name="cost1" size="7" onChange="calc_total()"
maxlength="7">&nbsp;</td>
</tr>
</table>
<hr>
<table id="totalcost" border="1">
<tr>
<td><input type="text" size="7" name="test" readonly>&nbsp;</td>
<td><input type "text" size="7" name="total" readOnly>&nbsp;</td>
</tr>
</table>
<input type="button" value="Add" onclick="addRowToTable();" />
<input type="button" value="Remove" onclick="removeRowFromTable();" />
</form>
</body>
</html>

<!-- Begin Add Row to Itemlist Table
function addRowToTable()
{
lastRow=1;
var tbl = document.getElementById('itemlist');
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

// qty cell
var qty = row.insertCell(0);
var el_qty = document.createElement('input');
el_qty.setAttribute('type', 'text');
el_qty.setAttribute('name', 'qty' + iteration);
el_qty.setAttribute('size', '7');
el_qty.setAttribute('maxlength', '7');
el_qty.setAttribute('onChange', 'calc_total()');
qty.appendChild(el_qty);

// price cell
var price = row.insertCell(1);
var el_price = document.createElement('input');
el_price.setAttribute('type', 'text');
el_price.setAttribute('name', 'price' + iteration);
el_price.setAttribute('size', '7');
el_price.setAttribute('maxlength', '4');
el_price.setAttribute('onChange', 'calc_total()');
price.appendChild(el_price);
}

//Remove a row from the table
function removeRowFromTable()
{
var tbl = document.getElementById('itemlist');
var last_Row = tbl.rows.length;
if (last_Row > 2) tbl.deleteRow(last_Row - 1);
}

// Calculate the total
function calc_total()
{
var num_of_units = document.myform.qty1.value;
var price_of_units = document.myform.cost1.value;
var total_cost = eval(num_of_units * price_of_units)
document.myform.total.value = total_cost;
}
//-->

I have not actually tried to understand your script at this time but I
have the following recommendations.

Can you change the onclick="addRow..." and onclick="removeRow..." to
onclick="addRow... ; calc_total;"
You can do multiple commands in the onclick.

The latest javascript has the following changes:
Remove language="javascript" and replace it with type="text/javascript"
Change readonly to readonly="readonly"

--
Dennis M. Marks
http://www.dcs-chico.com/~denmarks/
Replace domain.invalid with dcsi.net
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
Jul 23 '05 #2

"rick" <rmsingh@no_spam_rogers.com> wrote in message
news:mW*********************@twister01.bloor.is.ne t.cable.rogers.com...
Can anyone help, I am try to create a simple form using a table, where a
user can fill out
quanty and price and have a total automatically calculated and inserted in
another field.
I stuck trying to figure out how expand this script to recalculate when rows are added or
removed.
My code so far.


I appreciate your comments but the problem is not calling 'calc_total' again
, but modifing
'calc_total' to recompute a new total including any new rows/fields that was
added or removed.
Thanks again........
Jul 23 '05 #3
Dennis M. Marks wrote:
rick <rmsingh@no_spam_rogers.com> wrote:
I am try to create a simple form using a table, where a user can fill
outquanty and price and have a total automatically calculated and inserted in
another field. I stuck trying to figure out how expand this script to
recalculate when rows are added or removed.

<script language="JavaScript" src="/javascript/testtables.js"></script>
As Dennis said, use <script type="text/javascript">
function addRowToTable() ....// price cell ....el_price.setAttribute('name', 'price' + iteration);
To be consistent with the current table, and allow looping in the
total_cost function, use 'cost' instead of 'price':

el_price.setAttribute('name', 'cost' + iteration);
function calc_total() {
var num_of_units = document.myform.qty1.value;
var price_of_units = document.myform.cost1.value;
var total_cost = eval(num_of_units * price_of_units)
document.myform.total.value = total_cost;
}


Now you can loop through all but the last table rows to get the total:

function calc_total() {
var rowcount = document.getElementById('itemlist').rows.length;
var subtotal=0;
for (i=0; i<rowcount-1; i++)
subtotal += (document.myform.elements('qty'+i).value *
document.myform.elements('cost'+i).value);
document.myform.total.value = subtotal;
}

Mike

Jul 23 '05 #4
Revision:

- I had trouble getting setAttribute to work - 'name=qtyN' 'name=costN'
weren't showing up in the table html, so I used the cell innerHTML to
create the input textboxes instead.

- I had to change the value of iteration to get the looping in
calc_total to work, same with deleting row 1 instead of the lastrow-1.

- re-calc whenever there's a number of rows change

....here's what I have so far, maybe give this a try.

function addRowToTable() {
var tbl = document.getElementById('itemlist');
var iteration = tbl.rows.length-1;
var row = tbl.insertRow(1);
var qty = row.insertCell(0); // qty cell
qty.innerHTML='<input type="text" name=qty'+iteration+' size=7
maxlength=7 onChange="calc_total()">';
var price = row.insertCell(1); // price cell
price.innerHTML='<input type="text" name=cost'+iteration+' size=7
maxlength=4 onChange="calc_total()">';
calc_total();
}

function removeRowFromTable() {
var tbl = document.getElementById('itemlist');
var last_Row = tbl.rows.length;
if (last_Row > 2)
tbl.deleteRow(1);
calc_total();
}

function calc_total() {
var rowcount = document.getElementById('itemlist').rows.length-1;
var subtotal=0;
var currcost=0;
var currqty=0;
for (var i=0; i<rowcount; i++) {
currqty = document.myform.elements('qty'+i).value;
currcost = document.myform.elements('cost'+i).value;
if ((currqty == "") || (currcost == "")) {
//ignore this row, it includes blanks
} else {
subtotal += (currqty * currcost);
}
}
document.myform.total.value = subtotal;
}

function showtableinnerhtml() {
alert(document.getElementById('itemlist').innerHTM L);
}

Jul 23 '05 #5

Thanks for all the help, I will try it tonight.
Jul 23 '05 #6

Now you can loop through all but the last table rows to get the total:

function calc_total() {
var rowcount = document.getElementById('itemlist').rows.length;
var subtotal=0;
for (i=0; i<rowcount-1; i++)
subtotal += (document.myform.elements('qty'+i).value *
This line is causing an error in Internet Explorer and Firefox, here it is
Error: document.myform.elements is not a function
document.myform.elements('cost'+i).value);
document.myform.total.value = subtotal;
}

Mike

Jul 23 '05 #7
Thanks mscir I've the idea now, I appreciate your help

Rick
Jul 23 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Building Blocks | last post by:
Hi, All I need is a simle calculate form script which contains this: A script that can handle text input, radio buttons, checkboxes, and dropdowns. Each one of these variables will contain a...
53
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is...
7
by: Jurek | last post by:
I have 10+ experience in C/C++ - mostly automation and graphics. I have never written any business apps though. Recently I've been asked to write a simple report that would calculate sales...
4
by: Rich_C | last post by:
I'm sure this is very simple, but I have very little experience with javascript -- and what I do know isn't helping me here. I have a simple form where users can enter a quantity (qty) and cost...
4
by: scota | last post by:
I am new to ASP.NET, C#. I have the following code which will not display the total Credits for all the records. It is printing "Total Credits: 0" instead of adding the credits. What am I...
1
by: deena22 | last post by:
hello, i'm using 'Access database' and VB 6.0. My database is named ' timesheet' and it contains a table named 'tabletimesheet'. The table contain the following fields: 'staffname, stafftype,...
4
by: NormAmst | last post by:
I have a list of CPU processing times and job durations for an entire department at work. There are 3 classifications I am maintaining. CPU time during peak hours , CPU time during non peak hours...
1
by: Sedigh | last post by:
Hi Everybody, I need to write a macro on my Excel sheet to calculate the average of cells for me. This is the code I have written but the average function is not working. Can you please let me...
8
by: Magesh | last post by:
Consider a block, fncall( ); /* tells me the current millisecond or something like that: time-1 */ {/* block of code for which I need to know the exec time ... ... ... } fncall( ); /* tells...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.