By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,179 Members | 2,192 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,179 IT Pros & Developers. It's quick & easy.

Adding Values of TextBoxes Together

P: n/a
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="JavaScript">
<!-- 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.value' 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
Share this Question
Share on Google+
15 Replies


P: n/a
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="JavaScript">
<!-- 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

P: n/a
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="JavaScript">
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.getElementById('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="calcTotalPub(this.form);"

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="description" content="Adds form content">
</head>
<body>
<script type="text/javascript">
function calcTotalPub(theForm){
var tempFed = theForm.elements['txtFedSup'].value;
var tempState = theForm.elements['txtStateSup'].value;
var tempCounty = theForm.elements['txtStateSupA'].value;
var tempCity = theForm.elements['txtCitySup'].value;

theForm.elements['txtTotalPub'].value = Number(tempFed)
+ Number(tempState)
+ Number(tempCounty)
+ 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="txtStateSup">txtStateSup<br>
<input type="text" name="txtStateSupA">txtStateSupA<br>
<input type="text" name="txtCitySup">txtCitySup<br>
<input type="text" name="txtTotalPub" value="--">txtTotalPub<br>
<input type="button" value="Add 'em"
onclick="calcTotalPub(this.form);"><br>
<input type="reset" onclick="reset();">
</form>
</body>
</html>
Jul 23 '05 #3

P: n/a

"crjunk" <cr****@earthlink.net> wrote in message
news:e4**************************@posting.google.c om...
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="JavaScript">
<!-- 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.value' 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

P: n/a
On Wed, 15 Sep 2004 20:39:29 GMT, Mick White
<mw******@BOGUSrochester.rr.com> 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

P: n/a
On Thu, 16 Sep 2004 00:27:56 GMT, RobG <rg***@iinet.net.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.formName, but
it's advisable to use document.forms['formName']. Similarly, it would be
best to use formObj.elements['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.elementName

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="description" 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(theForm){
var tempFed = theForm.elements['txtFedSup'].value;
var tempState = theForm.elements['txtStateSup'].value;
var tempCounty = theForm.elements['txtStateSupA'].value;
var tempCity = theForm.elements['txtCitySup'].value;
Validation should go here.
theForm.elements['txtTotalPub'].value = Number(tempFed)
+ Number(tempState)
+ Number(tempCounty)
+ 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="calcTotalPub(this.form);"><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

P: n/a
On Wed, 15 Sep 2004 20:30:55 -0400, Hal Rosser <hm******@bellsouth.net>
wrote:
"crjunk" <cr****@earthlink.net> wrote in message
news:e4**************************@posting.google.c om...


[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

P: n/a
"Michael Winter" <M.******@blueyonder.co.invalid> wrote in message news:<opseexp3six13kvk@atlantis>...
On Wed, 15 Sep 2004 20:30:55 -0400, Hal Rosser <hm******@bellsouth.net>
wrote:
"crjunk" <cr****@earthlink.net> wrote in message
news:e4**************************@posting.google.c om...


[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

P: n/a
JRS: In article <g6*****************@news.optus.net.au>, dated Thu, 16
Sep 2004 00:27:56, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9

P: n/a
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

P: n/a
Michael Winter wrote:
[snip]
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.


I'd read FAQ 4.21 and followed the link to type conversion
and even read: "var numValue = (+stringValue);" but that
doesn't mean it sank in! I guess the syntax tricked me so I
didn't pick up on exactly what was going on - it makes sense
now.
[snip]
</head>
<body>
This creates invalid HTML. Remove these two tags.


Ooops - cutting and pasting between editor and news client
can have unexpected results. I have since realised that I
need to also test by cutting from the news client back to
the editor...
[snip]
It's usually better to validate on the form, rather than button click.
You mean use onblur or similar so validation happens per
element immediately? That's a design choice I figure - my
principle is lead gently, least annoyance, least surprise.
crjunk can work out what's best here.
[snip]
<input type="reset" onclick="reset();">
You don't include a reset function. I doubt one is needed, anyway.


All the forms I've done lately have needed custom reset
functions, guess I just got stuck in the mould - it's
included here for convenience.
[snip]
By the way, thank you for making the effort to drop F4D.


You noticed? <blush> :-)

Jul 23 '05 #11

P: n/a
On Thu, 16 Sep 2004 23:30:44 GMT, RobG <rg***@iinet.net.auau> wrote:

[snip]
Ooops - cutting and pasting between editor and news client can have
unexpected results.


Yes, I'm all too well aware, myself. :(

[snip]

[MW:]
It's usually better to validate on the form, rather than button click.


You mean use onblur or similar so validation happens per element
immediately?


No, I meant via the submit intrinsic event. I seem to remember problems
when trying to cancel a form submission be cancelling the button click.
Furthermore, if the user uses Enter to submit the form, a click event may
not be fired[1].

As for using the blur event, that should be avoided unless you have
specific reasons to do something *every* time the control loses focus.
This is because combining the focus method and blur (a common combination)
can result in a focus circle where the only option left to the user is to
forcably close the browser. Using the change event prevents this.
Moreover, the user will get very frustrated with repeated warnings about
invalid entries; change will only notify once until the value is altered.

Validation can have quite a few surprising usability issues associated
with it, and many people aren't aware of them. This is generally because
they don't use a page to the point where they would become noticable. For
example, you might want the user to enter a date in a specific format. If
they don't use that format, you want to tell them about it, re-focus the
control, and get it corrected. If all you do as a test is enter a wrong
value, try to change focus, correct the value, and leave again, you miss
something: what if the user is unable to enter the correct value at that
precise moment in time, or if they'd simply prefer to enter a value in
another control, first? They can't as you've locked them in that control.
Maybe not a particularly good example, but it demonstrates the point.

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


You noticed? <blush> :-)


Yup. Change of e-mail address, proper quoting, and you mentioned getting
used to your new client. The last one's a bit of a give away. :P

Mike
[1] I think some browsers do fire the event to allow scripts to work with
keyboard navigation.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #12

P: n/a
On Thu, 16 Sep 2004 23:57:20 GMT, Michael Winter wrote:
On Thu, 16 Sep 2004 23:30:44 GMT, RobG <rg***@iinet.net.auau> wrote:

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


You noticed? <blush> :-)


Yup. Change of e-mail address, proper quoting, and you mentioned getting
used to your new client. The last one's a bit of a give away. :P


I missed most of the hints, but had noticed your
responses were now 'threading' properly.

(..and I'll add my thanks as well, for that alone)

--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
Jul 23 '05 #13

P: n/a
RobG wrote:
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.
[...]


Your code has some serious issues.


As your posting has. Particularly, it by far exceeds the accepted 80
characters per line. Mozilla/5.0 does not have problems with borken
quote as OE does have, so you really should adjust your settings.
Automatic line-break at column 76 is good, at column 72 is better
(because more quotation levels are possible without reformatting the
quotes).
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.


Nonsense. The element's ID is _not_ used as a variable here but as a
property of the object referred to by `document'. That referencing
originates from DOM Level 0 (IE3/NN3) and works in many user agents,
including Mozilla/5.0. However, the standards compliant referencing

document.forms['Form1'].elements['txtFedSup'].value

as specified in DOM Level 1+ is very likely to work in *all* UAs as it
is downwards compatible to DOM Level 0.

See also

<http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/form.html>
<http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/form.asp>
<http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268>
The "+" should not be there - I don't know what you are trying
to achieve with it.
Nonsense. The OP is using the unary "+" operator as the fastest method
to convert a value (here: of type "string") to type "number".
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 [...]


No, it will not. Instead, it will return a very much predictable result,
i.e. an array or a collection of elements with that name as it has been
since DOM Level 0. Unfortunately, that Array/HTMLCollection object will
most certainly not have a "value" property which is why this will store
NaN (the result of +undefined) in `tempCounty' then. Yet a very much
predictable result.
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.getElementById('Form1');
getElementById() is a method of DOM Level 1+ and is not supported in
every UA, see above. More, it is less efficient than using the "forms"
collection:
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;
[...]
Below is code similar to yours that will work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
The required system identifier (the URL of the DTD) is missing here. This
will trigger Quirks/Compatibility Mode in some UAs and is therefore likely
to produce unpredictable rendering results. Correct is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

See <http://www.w3.org/TR/html4/struct/global.html#h-7.2>.
<html>
<head>
<title> add em </title>
<meta name="description" content="Adds form content">
When using "meta" elements for inclusion of document meta information,
well-defined Dublin Core Metadata Terms should be used, not a proprietary
approach:

<meta name="DC.Description" content="Adds form content">

See <http://dublincore.org/documents/dcmi-terms/>.

Furthermore, as intrinsic event handler attributes are used, it is
recommended to specify the default scripting language:

<meta http-equiv="Content-Script-Type" content="text/javascript">

See <http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.2.1>.

However, IE will ignore this element and uses the language specified
for the previous script element instead.
</head>
<body>
<script type="text/javascript">
function calcTotalPub(theForm){
var tempFed = theForm.elements['txtFedSup'].value;
var tempState = theForm.elements['txtStateSup'].value;
var tempCounty = theForm.elements['txtStateSupA'].value;
var tempCity = theForm.elements['txtCitySup'].value;

theForm.elements['txtTotalPub'].value = Number(tempFed)
+ Number(tempState)
+ Number(tempCounty)
+ Number(tempCity);
}
</script>
</head>
<body>
1. Nesting error: The "head" element is closed again after the open
tag of the "body" element, and the "body" element is opened a
second time after the second </head> close tag.

2. Functions should not be declared within the "body" element but
within the "head" element, to make sure that they are declared
when called within the "body" element.

3. This function declaration contains four superfluous variable
declarations and causes even more superfluous lookup operations,
while it does check neither for arguments nor references to DOM
objects prior to access; I already mentioned that the unary "+"
is the most efficient method for conversion to number. This
much better is

function calcTotalPub(o)
{
var o2 = null;
if (o
&& (o = o.elements)
&& (o2 = o['txtTotalPub'])
&& typeof o2.value != "undefined")
{
o2.value =
(o['txtFedSup'] ? +o['txtFedSup'].value : 0)
+ (o['txtStateSup'] ? +o['txtStateSup'].value : 0)
+ (o['txtStateSupA'] ? +o['txtStateSupA'].value : 0)
+ (o['txtCitySup'] ? +o['txtCitySup'].value : 0);
}
}
<h2>Here is the form</h2>
<form name="Form1">
A "form" element does not need to have a name, and since the name is used no
longer, it does not need to have one here. Instead, an "action" attribute
value is "#REQUIRED":

<form action="...">

See <http://www.w3.org/TR/html4/interact/forms.html#h-17.3>.
<input type="text" name="txtFedSup">txtFedSup<br>
<input type="text" name="txtStateSup">txtStateSup<br>
<input type="text" name="txtStateSupA">txtStateSupA<br>
<input type="text" name="txtCitySup">txtCitySup<br>
<input type="text" name="txtTotalPub" value="--">txtTotalPub<br>
Since "TEXT" is the initial value for the "type" attribute of the
"input" element, this attribute-value pair can be safely omitted:

<input name="txtFedSup">txtFedSup<br>
...

See <http://www.w3.org/TR/html4/interact/forms.html#h-17.4>.
<input type="button" value="Add 'em"
onclick="calcTotalPub(this.form);"><br>
Since this button only works if client-side script support is present,
it should be written dynamically to avoid confusion/irritation among
users of client applications without that feature:

<script type="text/javascript">
document.write(
'<input type="button" value="Add \'em"'
+ ' onclick="calcTotalPub(this.form);"><br>');
</script>
<input type="reset" onclick="reset();">


You have no reset() method defined but you call it in your code, BTW
completely unnecessarily.

After all, I would not call your code a good example, it is more like
once more an example of how not to do it.
PointedEars
--
He said: "Son, you are a technical boy..."
Jul 23 '05 #14

P: n/a
Thomas 'PointedEars' Lahn wrote:
3. [...] This much better is


s/This/Thus/
PointedEars, not to be misunderstood
--
I wish you get Better & Better with Gecko
Jul 23 '05 #15

P: n/a
Thomas 'PointedEars' Lahn wrote:
RobG wrote:

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.
[...]


Your code has some serious issues.

As your posting has. Particularly, it by far exceeds the accepted 80
characters per line. Mozilla/5.0 does not have problems with borken
quote as OE does have, so you really should adjust your settings.
Automatic line-break at column 76 is good, at column 72 is better
(because more quotation levels are possible without reformatting the
quotes).


Mozilla may not have a problem with broken quoting, but yours seems to
have a problem with its spell-checker and its ability to only post a
response once. Practice what you preach, before you start preaching.

To RobG: Ignore the ramblings of PointedEars, we are still anxiously
awaiting his exit from puberty, at which time he may (but probably
won't) exhibit the signs of having above a 3rd grade mentality.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Jul 23 '05 #16

This discussion thread is closed

Replies have been disabled for this discussion.