View Single Post
Old 02-13-2013, 06:54 PM   PM User | #4
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,100
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
c5=formatinput(document.form.c5.value);


It is very bad practice to use the same name such as c5 or sum for an HTML element and a Javascript variable. It leads to a lot of trouble.

Also, you should use the var keyword to make your variables local to the function, and not global which is the case if the var keyword is omitted.

Although the default of an input field is "text" you should still specify it.

To round a display value to x decimal places, use .toFixed(x). Note that the value then becomes a string so cannot be used in any further arithmetic calculations.

What is the point of your formatinput() function? You change a string value (as input by the user) into a number with Number() and trap NaN errors with

var c5val = Number(document.form.c5.value) || 0; // value is 0 if the conversion to a number results in NaN

Numbers by default are real (floating point). If you want an integer value use Math.floor() or Math.round(). Or block the entry of decimal points in the input field.

If you want to perform your calculation onchange (not onChange), you must assign a default value of 0 to the two input fields. Otherwise NaN occurs.
__________________

All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.

Last edited by Philip M; 02-13-2013 at 07:06 PM..
Philip M is offline   Reply With Quote
Users who have thanked Philip M for this post:
moonbeam429 (02-13-2013)