473,626 Members | 3,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to calculate row total in dynamic form?

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 totals for
a grand total.

can someone point me in the right direction?
<form action="purchas e_req1.asp" method="post" name="purchreq"
onsubmit="retur n validate();">
<table id="itemlist" width="100%">
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6"></td>
<td valign="top" height="15">[PUT TOTAL HERE]</td>
</tr>
<tr>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15">[PUT GRAND TOTAL HERE]</td>
</tr>
</table>
</form>

Jun 18 '06 #1
4 6363
Rich_C wrote:
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 totals for
a grand total.

can someone point me in the right direction?
<form action="purchas e_req1.asp" method="post" name="purchreq"
onsubmit="retur n validate();">
<table id="itemlist" width="100%">
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6"></td>
<td valign="top" height="15">[PUT TOTAL HERE]</td>
</tr>
<tr>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15">[PUT GRAND TOTAL HERE]</td>
</tr>
</table>
</form>


Off the top of my head, I'd start with something like...

In the doument head:

<script type="text/javascript">
function updateTotal(f)
{
var total = parseInt(f.qty. value, 10) * parseFloat(f.co st.value, 10);
var cell = document.getEle mentById("total ");
while (cell.firstChil d) cell.removeChil d(cell.firstChi ld);
cell.appendChil d(document.crea teTextNode(tota l.toString()));
}
</script>

Then your form would be...

<form action="purchas e_req1.asp" method="post" name="purchreq"
onsubmit="retur n validate();">
<table id="itemlist" width="100%">
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4" onchange="updat eTotal(this.for m)"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6" onchange="updat eTotal(this.for m)></td>
<td valign="top" height="15">[PUT TOTAL HERE]</td>
</tr>
<tr>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15"></td>
<td valign="top" height="15" id="total">[PUT GRAND TOTAL HERE]</td>
</tr>
</table>
</form>
Jun 18 '06 #2
TheBagbournes wrote on 18 jun 2006 in comp.lang.javas cript:
<script type="text/javascript">
function updateTotal(f)
{
var total = parseInt(f.qty. value, 10) * parseFloat(f.co st.value,
10); var cell = document.getEle mentById("total ");
while (cell.firstChil d) cell.removeChil d(cell.firstChi ld);
cell.appendChil d(document.crea teTextNode(tota l.toString()));
}
</script>

Then your form would be...

<form action="purchas e_req1.asp" method="post" name="purchreq"
onsubmit="retur n validate();">
<table id="itemlist" width="100%">
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4" onchange="updat eTotal(this.for m)"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6" onchange="updat eTotal(this.for m)></td>
<td valign="top" height="15">[PUT TOTAL HERE]</td>
</tr>

This works in a multirow table on each row separately:

<script type="text/javascript">
function updateTotal(x){
var myRow = x.parentNode.pa rentNode
myRow.cells[2].innerHTML =
parseInt(
myRow.cells[0].getElementsByT agName('INPUT')[0].value,10)*
parseFloat(
myRow.cells[1].getElementsByT agName('INPUT')[0].value,10);
}
</script>

<form onsubmit="retur n false">
<table>

<tr>
<td>
Qty:
<input type="text"
onchange="updat eTotal(this)">
</td>

<td name="cost">
Cost:
<input type="text"
onchange="updat eTotal(this)">
</td>

<td name='total'>
[PUT TOTAL HERE]
</td>
</tr>

<tr>
<td>
Qty:
<input type="text"
onchange="updat eTotal(this)">
</td>

<td name="cost">
Cost:
<input type="text"
onchange="updat eTotal(this)">
</td>

<td name='total'>
[PUT TOTAL HERE]
</td>
</tr>

</table>
</form>

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jun 18 '06 #3
Rich_C wrote:
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 totals for
a grand total.


Below is something that should help. Note that you must validate input
before trying to do maths with it. Presuming you are using $ and
cents, work in whole cents internally, display as $ only for output -
same for any other currency. Read the FAQ on rounding and maths in
JavaScript - unless you *want* to work in decimal cents, in which case
you'd better decide how many decimal places you want to work to, then
bone-up on rounding and the precision of maths in JavaScript (there are
many posts in the archives).

And remember that anyone with JavaScript disabled or not available
won't see the results.
<!-- Note that form must be cleared of values on page load,
or change function to update entire table onload and onchange
-->

<body onload="documen t.forms[0].reset();">

<script type="text/javascript">

// Updates row where input changed, re-calcs grand total
function update(el)
{
// Get the parent TR
var tr = el.parentNode;
while (tr.nodeName.to LowerCase() != 'tr'){
tr = tr.parentNode;
}

// Get the qty and cost values from the inputs
var qty = tr.cells[0].getElementsByT agName('input')[0].value;
var cost = tr.cells[2].getElementsByT agName('input')[0].value;

/* code here to validate input of qty and cost as
integer or float as appropriate
*/

// Do all arithmatic in cents or equivalent in whatever
// decimal currency is being used
var total = Math.round(qty* cost*100);

// Display total formatted for decimal currency
tr.cells[3].innerHTML = cToD(total);

// Do grand total
var rows = tr.parentNode.r ows;
var i = rows.length;
var gTotal = 0;
while (i--){
gTotal += rows[i].cells[3].innerHTML * 100;
}
document.getEle mentById('grand Total').innerHT ML = cToD(gTotal);
}

// Simple function to convert decimal currency
function cToD(c)
{
if (c<10) return '0.0' + c;
if (c<100) return '0.' + c;
c += '';
return (c.substring(0, c.length-2)) + '.'
+(c.substring(c .length-2));
}

</script>

<form action="purchas e_req1.asp" method="post" name="purchreq"
onsubmit="retur n validate();">
<table id="itemlist">
<thead align="left">
<th>Qty</th>
<th>Description </th>
<th>Cost $</th>
<th>Total $</th>
</thead>

<!-- This table section holds the items, it needs to be independent
of other table sections
-->
<tbody id="items">
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4" onchange="updat e(this);"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6" onchange="updat e(this);"></td>
<td valign="top" height="15" align="right"></td>
</tr>
<tr>
<td valign="top" height="15"><in put type="text" name="qty"
size="4" onchange="updat e(this);"></td>
<td valign="top" height="15"><te xtarea name="desc" rows="4"
cols="40"></textarea>
<td valign="top" height="15"><in put type="text" name="cost"
size="6" onchange="updat e(this);"></td>
<td valign="top" height="15" align="right"></td>
</tr>
</tbody>

<!-- This table section holds the grand total, it needs to be
independent of other table sections
-->
<tbody>
<tr>
<td colspan="3" height="15"><b> Grand Total</b></td>
<td valign="top" height="15" id="grandTotal " align="right">0 </td>
</tr>
</tbody>
</table>
</form>

</body>
--
Rob

Jun 19 '06 #4
JRS: In article <11************ *********@c74g2 000cwc.googlegr oups.com>,
dated Sun, 18 Jun 2006 18:12:38 remote, seen in
news:comp.lang. javascript, RobG <rg***@iinet.ne t.au> posted :
Presuming you are using $ and
cents, work in whole cents internally, display as $ only for output -
same for any other currency.


That applies in the OP's case.
It occurs to me, however, that if VAT, sales taxes, etc., become
involved, then merely working in cents may not be sufficient.

VAT here adds 17.5% to the price, which is +7/40, so one could get exact
results by working in hundredths of a cent; but the tax is 7/47 of the
purchase price...

In any such case, it is essential that the official rules for
calculation be followed.
There has been recent discussion, in news:borland.pu blic.attachment s and
news:borland.pu blic.delphi.lan guage.delphi.ge neral, of a Decimal Math
Unit. Like Javascript, Delphi has no direct support for decimal
arithmetic.

In Javascript terms, IIRC AFAICS &c, the idea is to represent a
"Decimal" as an Object containing an integer Mantissa part, an integer
part representing a base-10 exponent, and parts indicating the desired
accuracy (i.e. 2 decimal places (generally) for tangible currency) and
type of rounding to apply. Operations would be performed by Methods.
It gives an accuracy of about 15 significant figures over a range
exceeding the wildest dreams of the Chancellor of the Exchequer.

The idea is that by using such one could exactly match the requirements
of law and accounting.

Note that if these represent Currency there should be no need for a
Multiply Together method.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jun 19 '06 #5

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

Similar topics

4
2135
by: pizzy | last post by:
INTRO: I tried to clean it up for easy reading. I hope I didn't make any mistakes. PROBLEM: WOW, this is some crazy sh!t. I can't get my checkbox (see "TAGSELECTED") to print my textboxes (see "TAG#") when more than 1 number (see "VLANS") is inputed into my form. QUESTION: How do I make my dynamic form have a dynamic input box(which is created by checking the checkbox and calling the functionC1) inside it and still be able to pass the...
0
1971
by: Pat Patterson | last post by:
I'm having serious issues with a page I'm developing. I just need some simple help, and was hoping someone might be able to help me out in here. I have a form, that consists of 3 pages of fields. I'd like to create a page in which all of this is stored as you move along as hidden variables, until the end, when the user submits. I can't figure out one thing: I have dynamic form elements (dropdowns), that I'd like to use instead of...
3
2936
by: CAD Fiend | last post by:
Hello, Well, after an initial review of my database by my client, they have completely changed their minds about how they want their form. As a result, I'm having to re-think the whole process. My Current Form (6 tabs): - Owner, Property, Title, Docs, Queries, & Reports - User is able to see (while navigating through the tabs) above in the form : Owner Name, Address, Parcel, and SSN
7
3575
by: Venus | last post by:
Hello, I am trying to generate a dynamic form at runtime and would like to do it using "<asp: ..." form elements as follows Build up the string that is placed somewhere in the HTML code the same way like regular input fields can. strForm = "<form name=""myForm"" runat=""server"">" & vbCrLf strForm += "<asp:button name=""myName"" .... runat=""server"" />" & vbCrLf
4
3301
by: Venus | last post by:
Hello, Thanks for your reply. I understand that a control can be created dynamically in several ways: 1) using StringBuilder 2) using Controls.Add 3) using ASP PlaceHolder But this is just for the controls and not for the form itself. What I am trying to achieve is to create an entire form (including controls)
0
1485
by: Venus | last post by:
Hello, After trying some ways to do it I wanted to use something like the code below but for some reason is not working (I have to generate the entire form dynamically (not only the controls)): Can anyone make any suggestions on how to do it ? Thanks
2
4659
by: 06mca30 | last post by:
How to calculate total no of hits for my home page?
3
2485
by: John Torres | last post by:
how do you calculate total time hours? I have sub total hours for each day and I've been trying to total all the hours. I'm getting odd numbers. Thanks. John
4
1843
by: libish | last post by:
hi all... can any one help me by suggesting a way to get items in dynamic form? here what i'm doing is , i'm displaying a dynamic form. in that form i have a main menu and this main menu contains a menu item "OK". here the dynamic form consist of some labels, list items and all. when i click on the "OK" menu item, an event occurs and i've wrote methods which wll execute on this event. now i need the selected list item index,value.. label...
0
8259
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
8192
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8696
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
8637
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
8358
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
8502
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7188
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
5571
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();...
0
4090
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

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.