473,847 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding Values of TextBoxes Together

I have 4 TextBoxes on my form that I'm trying to add together to get a
grand total. Here is the code I'm using:

<SCRIPT LANGUAGE="JavaS cript">
<!-- Beginning of JavaScript -

function calcTotalPub()
{
var tempFed = +document.Form1['txtFedSup'].value;
var tempState = +document.Form1['txtStateSup'].value;
var tempCounty = +document.Form1['txtStateSup'].value;
var tempCity = +document.Form1['txtCitySup'].value;

document.Form1['txtTotalPub'].value = tempFed + tempState +
tempCounty + tempCity ;
}

// - End of JavaScript - -->
</SCRIPT>

After I type in a value into my txtFedSup TextBox and click out of it,
I receive the following error message: "
'document.Form1 .txtFedSup.valu e' is null or not an object "

I have a number typed into the txtFedSup field and I also have the
number zero typed into the remaing TextBoxes as a default value, but
I'm still receiving this null error message.

Can anyone tell me what I'm doing wrong? I'm not very experienced
with JavaScripts.

Thanks,
C.R. Junk
Jul 23 '05 #1
15 12410
crjunk wrote:
I have 4 TextBoxes on my form that I'm trying to add together to get a
grand total. Here is the code I'm using:

<SCRIPT LANGUAGE="JavaS cript">
<!-- Beginning of JavaScript -

function calcTotalPub()
{
var tempFed = +document.Form1['txtFedSup'].value;
What if you use: Number(document .Form1['txtFedSup'].value) ?
And is that a correct reference to the textfield?
Mick

var tempState = +document.Form1['txtStateSup'].value;
var tempCounty = +document.Form1['txtStateSup'].value;
var tempCity = +document.Form1['txtCitySup'].value;

document.Form1['txtTotalPub'].value = tempFed + tempState +
tempCounty + tempCity ;
}

// - End of JavaScript - -->
</SCRIPT>

Jul 23 '05 #2
crjunk wrote:
I have 4 TextBoxes on my form that I'm trying to add together to get a
grand total. Here is the code I'm using:
<snip>
Can anyone tell me what I'm doing wrong? I'm not very experienced
with JavaScripts.

Thanks,
C.R. Junk

Your code has some serious issues. Taking it from the top:
<SCRIPT LANGUAGE="JavaS cript">
Use:

<script type="text/javascript">
var tempFed = +document.Form1['txtFedSup'].value;
I presume you have created a form with id="Form1". The syntax you've used only works in IE, that is, using the element ID "Form1" as a global variable. The "+" should not be there - I don't know what you are trying to achieve with it.

You have calls to two text boxes with the same name:
var tempCounty = +document.Form1['txtStateSup'].value;


so referencing them by name will give unpredictable results (most likely failure). I've changed the name of one of them - unless you really want to add the same value twice, or you only meant to have one of the calls.

You can get a reference to the table using the ID as follows:

var theTable = document.getEle mentById('Form1 ');

Or you can use the name of the form as follows (presuming you have made the name="Form1"):

var tempFed = document.forms['Form1'].elements['txtFedSup'].value;

Even better, when the user clicks on the "add 'em" button, you can simply use:

onclick="calcTo talPub(this.for m);"

to pass a reference to the current form to the calc function - no need for id or name. It means your calc function is more abstracted. Going further, you could just find all the text boxes in your form and add them, rather than explicitly finding each value by name but I'll leave that up to you.

You also must convert your strings to numbers before adding, otherwise you will get string concatenation. Read here:

http://www.jibbering.com/faq/#FAQ4_21

You may want to add formatting to guarantee two decimal places rather than integers. Also, add validation to ensure appropriate text has been entered - if something other than a number is entered using the code below, an error will result. Lastly, you should consider disabling the total box so users can't just put whatever they want in there - unless you want them to be able to.

Below is code similar to yours that will work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title> add em </title>
<meta name="descripti on" content="Adds form content">
</head>
<body>
<script type="text/javascript">
function calcTotalPub(th eForm){
var tempFed = theForm.element s['txtFedSup'].value;
var tempState = theForm.element s['txtStateSup'].value;
var tempCounty = theForm.element s['txtStateSupA'].value;
var tempCity = theForm.element s['txtCitySup'].value;

theForm.element s['txtTotalPub'].value = Number(tempFed)
+ Number(tempStat e)
+ Number(tempCoun ty)
+ Number(tempCity );
}
</script>
</head>
<body>
<h2>Here is the form</h2>
<form name="Form1">
<input type="text" name="txtFedSup ">txtFedSup <br>
<input type="text" name="txtStateS up">txtStateSup <br>
<input type="text" name="txtStateS upA">txtStateSu pA<br>
<input type="text" name="txtCitySu p">txtCitySup<b r>
<input type="text" name="txtTotalP ub" value="--">txtTotalPub<b r>
<input type="button" value="Add 'em"
onclick="calcTo talPub(this.for m);"><br>
<input type="reset" onclick="reset( );">
</form>
</body>
</html>
Jul 23 '05 #3

"crjunk" <cr****@earthli nk.net> wrote in message
news:e4******** *************** ***@posting.goo gle.com...
I have 4 TextBoxes on my form that I'm trying to add together to get a
grand total. Here is the code I'm using:

<SCRIPT LANGUAGE="JavaS cript">
<!-- Beginning of JavaScript -

function calcTotalPub()
{
var tempFed = +document.Form1['txtFedSup'].value; =============== =============== ==============
*************** *************** *************** *****
Should that be
var tempFed += document.forms[0].element[0].value
??
*************** *************** *************** *****
=============== =============== =============== var tempState = +document.Form1['txtStateSup'].value;
var tempCounty = +document.Form1['txtStateSup'].value;
var tempCity = +document.Form1['txtCitySup'].value;

document.Form1['txtTotalPub'].value = tempFed + tempState +
tempCounty + tempCity ;
}

// - End of JavaScript - -->
</SCRIPT>

After I type in a value into my txtFedSup TextBox and click out of it,
I receive the following error message: "
'document.Form1 .txtFedSup.valu e' is null or not an object "

I have a number typed into the txtFedSup field and I also have the
number zero typed into the remaing TextBoxes as a default value, but
I'm still receiving this null error message.

Can anyone tell me what I'm doing wrong? I'm not very experienced
with JavaScripts.

Thanks,
C.R. Junk

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.754 / Virus Database: 504 - Release Date: 9/6/2004
Jul 23 '05 #4
On Wed, 15 Sep 2004 20:39:29 GMT, Mick White
<mw******@BOGUS rochester.rr.co m> wrote:
crjunk wrote:


[snip]
var tempFed = +document.Form1['txtFedSup'].value;


What if you use: Number(document .Form1['txtFedSup'].value) ?


Why should that make a difference? Both result in an internal ToNumber
call.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
On Thu, 16 Sep 2004 00:27:56 GMT, RobG <rg***@iinet.ne t.auau> wrote:
crjunk wrote:
[snip]
var tempFed = +document.Form1['txtFedSup'].value;


I presume you have created a form with id="Form1".


Not necessarily. You can access a named form using document.formNa me, but
it's advisable to use document.forms['formName']. Similarly, it would be
best to use formObj.element s['elementName']; I don't know if that's the
source of the problem.
The syntax you've used only works in IE, that is, using the element ID
"Form1" as a global variable.
The usual pattern for that would be

Form1.elementNa me

but otherwise, you're correct: that syntax should be avoided.
The "+" should not be there - I don't know what you are trying to
achieve with it.
It shouldn't be in that exact location - validation of the entry should
come first - but it is correct. Read the FAQ: unary plus is generally the
fastest way to convert a string to a number.

[snip]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
I'd advise you to use an up-to-date DOCTYPE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> add em </title>
<meta name="descripti on" content="Adds form content">
Don't forget to specify the character set:

<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
</head>
<body>
This creates invalid HTML. Remove these two tags.
<script type="text/javascript">
function calcTotalPub(th eForm){
var tempFed = theForm.element s['txtFedSup'].value;
var tempState = theForm.element s['txtStateSup'].value;
var tempCounty = theForm.element s['txtStateSupA'].value;
var tempCity = theForm.element s['txtCitySup'].value;
Validation should go here.
theForm.element s['txtTotalPub'].value = Number(tempFed)
+ Number(tempStat e)
+ Number(tempCoun ty)
+ Number(tempCity );
[snip]
<form name="Form1">
FORMs require action attributes. For examples,

action=""

will do. When you submit the form, the current page will be reloaded, with
the GET parameters in the URI.

[snip]
<input type="button" value="Add 'em"
onclick="calcTo talPub(this.for m);"><br>
It's usually better to validate on the form, rather than button click.
<input type="reset" onclick="reset( );">


You don't include a reset function. I doubt one is needed, anyway.

[snip]

By the way, thank you for making the effort to drop F4D.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6
On Wed, 15 Sep 2004 20:30:55 -0400, Hal Rosser <hm******@bells outh.net>
wrote:
"crjunk" <cr****@earthli nk.net> wrote in message
news:e4******** *************** ***@posting.goo gle.com...


[snip]
var tempFed = +document.Form1['txtFedSup'].value;

=============== =============== ==============
*************** *************** *************** *****
Should that be
var tempFed += document.forms[0].element[0].value


Nope. Unary plus converts strings to numbers. However, the value should be
validated first.

[snip]

Mike
Please remember to trim quoted material that your response doesn't concern.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #7
"Michael Winter" <M.******@bluey onder.co.invali d> wrote in message news:<opseexp3s ix13kvk@atlanti s>...
On Wed, 15 Sep 2004 20:30:55 -0400, Hal Rosser <hm******@bells outh.net>
wrote:
"crjunk" <cr****@earthli nk.net> wrote in message
news:e4******** *************** ***@posting.goo gle.com...


[snip]
var tempFed = +document.Form1['txtFedSup'].value;

=============== =============== ==============
*************** *************** *************** *****
Should that be
var tempFed += document.forms[0].element[0].value


Nope. Unary plus converts strings to numbers. However, the value should be
validated first.

[snip]

Mike
Please remember to trim quoted material that your response doesn't concern.


I've been playing around with everyone's suggestions, but I'm having
no luck. Part of my problem might be because this script is running
in an ASP.Net web form. Although the script is located in my main web
form, the TextBoxes are in a user control that is pulled into the main
web form.
Jul 23 '05 #8
JRS: In article <g6************ *****@news.optu s.net.au>, dated Thu, 16
Sep 2004 00:27:56, seen in news:comp.lang. javascript, RobG
<rg***@iinet.ne t.auau> posted :

I presume you have created a form with id="Form1". The syntax you've used only
works in IE, that is, using the element ID "Form1" as a global variable. The
"+" should not be there - I don't know what you are trying to achieve with it.


Before you answer question, you should read and understand the newsgroup
FAQ; and probably re-read the parts specific to the question.

See FAQ 4.21, sentence 1 (of 2), last "word".

Richard - since that seems to be the preferred method, could it be made
more conspicuous?

See also FAQ 2.3 para 1 links contents (probably), and set your right
margin to 72 characters, in order that all can readily read what you
write. It is the usenet norm.

Andrew - I think you overdo (underdo?) it!

--
© 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.
Jul 23 '05 #9
On Thu, 16 Sep 2004 13:27:00 +0100, Dr John Stockton wrote:
Andrew - I think you overdo (underdo?) it!


Anything worth
doing, is worth
overdoing. ;-)
Jul 23 '05 #10

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

Similar topics

3
1726
by: Aaron Ackerman | last post by:
I have a bound combobox the appears on a cell within the column of my bound grid when the user clicks on a cell n(In my vb.net WinForm app). I am trying to allow the adding of an item to that bound combo by allowing the user to dynamically type in the new value directly in the combo box whcih in turn updates the lookup table and then when they have finished leaves that particular cell on the grid with the correct value. Seems...
4
309
by: Tonya | last post by:
Hi All, I wanted to ask how i can add values from textboxes etc into a specific coloumn and row of a datagrid. I.e does the datagrid have coordinates that i can refernce when i want to add values. e.g if i want to add a value to the second row and second column do i write coordinates such as.. (2,2)
15
8123
by: Stormkid | last post by:
Hey Gang, I'm trying to figure out the best way to add two times together of the format hh:mm:ss any suggestions would be great thanks Todd
1
1399
by: Arjen Hoekstra | last post by:
Hello, I've got a datagrid with a textbox in each cell. I've also two buttons, one to add a row to the datagrid and one to delete a row. A user can type data into textboxes and then submit it to a database (by clicking on a submit button). The problem is that every time, the "add row" or "delete row" button is clicked, the textbox values in the datagird are emptied, because when the page postbacks it gets the latest datatable from a...
13
21578
by: moondaddy | last post by:
my understanding is that the max value of a byte is 255. Therefore, why does the following code get a compile error? byte val1 = 10; byte val2 = 23; byte ttl; ttl = val1 + val2; //this line wont compile compile error: Cannot implicitly convert type 'int' to 'byte'.
4
3023
by: David Plotts | last post by:
I'm a beginner with VB.net, only had one class in college on it. I can't seem to remember how to add text boxes up. I want to add the values in text boxes together, and put the value into a label This is what I have, but it just adds the values together. So if txt_roads_pre.text has 5, and txt_parking_pre.text has 6, lbl_impervious_pre.text would have "56"
3
2472
by: someguy | last post by:
I am developing a shopping cart and have come across a problem. I have developed it in such a way that there is two carts, I call them the user_cart and the session_cart,, but they all really go to the same place and are only differentiated by the user_id or the cfid columns (one OR the other). I have developed them this way in case one use may have more than one account without cross-breeding information. When the user logs in, any items in...
1
2124
by: jyothi1105 | last post by:
Hi, I want to add textboxes and labels at runtime. Controls are to be added according to the value entered in textbox. txtfamily is a textbox,in which user gives the no of familymembers. i want to add age,gender,notes for each member.I have to repeat this process for total no of family members. Iam trying this code below, please help me..iam not getting exactly what i wanted. Private Sub txtfamily_TextChanged(ByVal sender As...
8
2731
by: Hypnotik | last post by:
Hey everyone. I'm writing a program which allows the user to enter information about 2 shapes, either a square, triangle, or rectangle, then 'adds' the shaps together. The resulting shape is a polygon. I understand how this is done, just not sure about the code. I need to overload the + operator to add the shapes. Also I know that I need to make a comparison between sides begin combined, and subtract the smaller side from the area. Also I...
0
9886
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
9730
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
10647
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
10706
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
9482
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...
1
7882
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5911
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4119
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3164
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.