473,769 Members | 7,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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>Testin g Tables Calculation</title>
<script language="JavaS cript" 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="addRow ToTable();" />
<input type="button" value="Remove" onclick="remove RowFromTable(); " />
</form>
</body>
</html>

<!-- Begin Add Row to Itemlist Table
function addRowToTable()
{
lastRow=1;
var tbl = document.getEle mentById('iteml ist');
var iteration = lastRow;
var row = tbl.insertRow(l astRow);

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

// price cell
var price = row.insertCell( 1);
var el_price = document.create Element('input' );
el_price.setAtt ribute('type', 'text');
el_price.setAtt ribute('name', 'price' + iteration);
el_price.setAtt ribute('size', '7');
el_price.setAtt ribute('maxleng th', '4');
el_price.setAtt ribute('onChang e', 'calc_total()') ;
price.appendChi ld(el_price);
}

//Remove a row from the table
function removeRowFromTa ble()
{
var tbl = document.getEle mentById('iteml ist');
var last_Row = tbl.rows.length ;
if (last_Row > 2) tbl.deleteRow(l ast_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_uni ts * price_of_units)
document.myform .total.value = total_cost;
}
//-->
Jul 23 '05 #1
7 2831
In article
<mW************ *********@twist er01.bloor.is.n et.cable.rogers .com>, rick
<rmsingh@no_spa m_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>Testin g Tables Calculation</title>
<script language="JavaS cript" 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="addRow ToTable();" />
<input type="button" value="Remove" onclick="remove RowFromTable(); " />
</form>
</body>
</html>

<!-- Begin Add Row to Itemlist Table
function addRowToTable()
{
lastRow=1;
var tbl = document.getEle mentById('iteml ist');
var iteration = lastRow;
var row = tbl.insertRow(l astRow);

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

// price cell
var price = row.insertCell( 1);
var el_price = document.create Element('input' );
el_price.setAtt ribute('type', 'text');
el_price.setAtt ribute('name', 'price' + iteration);
el_price.setAtt ribute('size', '7');
el_price.setAtt ribute('maxleng th', '4');
el_price.setAtt ribute('onChang e', 'calc_total()') ;
price.appendChi ld(el_price);
}

//Remove a row from the table
function removeRowFromTa ble()
{
var tbl = document.getEle mentById('iteml ist');
var last_Row = tbl.rows.length ;
if (last_Row > 2) tbl.deleteRow(l ast_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_uni ts * 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="remove Row..." to
onclick="addRow ... ; calc_total;"
You can do multiple commands in the onclick.

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

--
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_spa m_rogers.com> wrote in message
news:mW******** *************@t wister01.bloor. is.net.cable.ro gers.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_spa m_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="JavaS cript" src="/javascript/testtables.js"> </script>
As Dennis said, use <script type="text/javascript">
function addRowToTable() ....// price cell ....el_price.setA ttribute('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.setAtt ribute('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_uni ts * price_of_units)
document.myfo rm.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.getEle mentById('iteml ist').rows.leng th;
var subtotal=0;
for (i=0; i<rowcount-1; i++)
subtotal += (document.myfor m.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.getEle mentById('iteml ist');
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'+itera tion+' size=7
maxlength=7 onChange="calc_ total()">';
var price = row.insertCell( 1); // price cell
price.innerHTML ='<input type="text" name=cost'+iter ation+' size=7
maxlength=4 onChange="calc_ total()">';
calc_total();
}

function removeRowFromTa ble() {
var tbl = document.getEle mentById('iteml ist');
var last_Row = tbl.rows.length ;
if (last_Row > 2)
tbl.deleteRow(1 );
calc_total();
}

function calc_total() {
var rowcount = document.getEle mentById('iteml ist').rows.leng th-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 showtableinnerh tml() {
alert(document. getElementById( 'itemlist').inn erHTML);
}

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.getEle mentById('iteml ist').rows.leng th;
var subtotal=0;
for (i=0; i<rowcount-1; i++)
subtotal += (document.myfor m.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
9993
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 number. That number will appear in a seperate box at the bottom. So basically whatever you choose has a corresponding number associated with it (except for the text input, which you enter whatever number) and those numbers are added and produced in...
53
5743
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 difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
7
4329
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 commission. The report needs to be generated from within a C/C++ app. I don't want to mess it up so I thought maybe someone from this group could give me some advice or point to me to a place that'll provide some background on the issue. Here is a...
4
6374
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 (cost). Users can dynamically add rows to the table so I don't know how many rows might need to be calculated. I need to calculate the total (qty * cost) and put that number in a table cell (or read only input box). I also need to sum the...
4
1710
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 missing? Credits is the 4th column in the datagrid and the 4th field in the SQL view. Credits data type is float. Thank you. protected void btnSubmit_Click(object sender, EventArgs e) {
1
7474
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, date, projectname, projectcode and hoursworked' . On my VB 6.0 form, i have got a ' list Box' containing the 'type of staff', for example 'engineer, manager or secretary'. I have got another 'list Box' containing the 'name of projects' . Also i have...
4
3020
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 and total CPU time. I developed an Excel spreadsheet totaling the times and manually format a spreadsheet to present total jobs run and total CPU time for the department. I also developed an Access 2002 db, where I import all the run job...
1
7300
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 know how can I use the Average function in my code. Thanks alot Sub Macro1() Ncol = 1 nrowColumn2 = 1 i = 1 Do Until IsEmpty(Worksheets(1).Cells(i, 1))
8
3779
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 me the current millisecond or something like that:
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10214
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10048
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9996
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3963
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.