View Single Post
Old 02-13-2013, 05:42 PM   PM User | #2
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,098
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
I am sorry to say that there are many errors.

You should not assign the same names/ids v1 etc. to HTML form elements and Javascript variables.

And even if there were such unduplicated form elements, you keep over-writing the value of elem.

If all you want to do is to multiply four fixed numbers together, then

Code:
var v1 = 10;
var v2 = 10;
var v3 = 0.3;
var v4 = 40;
var ans = v1 * v2 *v3 * v4;  // you must not assign the same name to an HTML element and a Javascript variable
document.getElementById("answer").value = ans;
If you are trying to perform calculations on numbers entered into fields by the user, then you have a great many problems, incluing validation of the inputs to ensure that they are numbers (within a sensible range). It is pointless to use onkeyup here. The calculation will only make sense if all four numbers have been entered. But you must rename or (re-id) your form fields so as to not duplicate the Javascript variables.

Be aware that form field values are strings unless/until converted to numbers by one of several methods, Number() being recommended.

Code:
var val1= Number(document.getElementById("v1").value) || 0;  // || 0 traps NaN entries and changes them to 0.
val1 = Math.floor(val1);  // (or Math.round) - make val1 integer 
// val1 is the name of the Javascript variable.  v1 is the id of the form field.
// Now check that val1 is within a sensible range, and (presumably) not negative.
Finally, put newlines between each line of your HTML code. It makes it unreadable if you run them all together into one long line.

onkeyup="javascript: setValue(this)"
javascript is completely unnecessary - I have forgotten exactly why in the distant past it was required in some early browsers.

Your style sheet is also purposeless. It specifies what are the default colors anyway. I would advise you not to try to bite off too much at one sitting - keep your early attempts simple and check them frequently to see if they run OK, then build on your work. Rather than Coffee Cup Editor I would recommend that you use plain old Notetab or Notepad++.

"In the beginner's mind there are many possibilities, but in the expert's mind there are few” - Shunryu Suzuki (Japanese Zen priest, ?-1971)
__________________

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 05:59 PM..
Philip M is offline   Reply With Quote