This is my first attempt at a script. I want it to accept a number with decimal point, and it will not. I altered it already once and it accepted decimal points, but then it stopped calculating the result. Var 2 and Var 3 are the only fields that need to have decimal points possible. Also, is it possible to recode this so var 3 can be entered as a whole number? I want the person to enter a profit percentage, like 30 for 30 percent, but I could only figure it out by making it 0.3 Any help would be greatly appreciated.
Code:
<script type="text/javascript" language="Javascript">
var v1 = 10;
var v2 = 10;
var v3 = 0.3;
var v4 = 40;
var answer = 1200;
function calculate () {
// The Calculation: change operator in this equation to change the calculation
answer = v1 * v2 * v3 * v4;
var elem;
elem = document.getElementById("v1");
elem.value = v1;
elem = document.getElementById("v2");
elem.value = v2;
elem = document.getElementById("v3");
elem.value = v3;
elem = document.getElementById("v4");
elem.value = v4;
elem = document.getElementById("answer");
elem.value = answer;
}
function setValue(elem) {
var val = 0.0;
if (elem.value != "") {
val = parseFloat(elem.value);
}
else {
val = 0.0;
}
switch (elem.id) {
case "v1": v1 = val; break;
case "v2": v2 = val; break;
case "v3": v3 = val; break;
case "v4": v4 = val; break;
}
calculate();
}
</script>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="created" content="Mon, 11 Feb 2013 17:31:53 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<title>Calculator</title>
<style type="text/css">
<!--
body {
color:#000000;
background-color:#FFFFFF;
}
a { color:#0000FF; }
a:visited { color:#800080; }
a:hover { color:#008000; }
a:active { color:#FF0000; }
-->
</style>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body onload="calculate();">
<div>Number of Employees</div> <form><input type="text" id="v1" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Hourly Rate<br /><input type="text" id="v2" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Markup Percentage<br /><input type="text" id="v3" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">*</span><br />Hours Per Week<br /><input type="text" id="v4" onkeyup="javascript: setValue(this);" /> <span style="color: #ffffff;">=</span><br />Your Weekly Profit<br /><input type="text" id="answer" readonly="" /></form>
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.
As I mentioned, this is my first attempt at javascript, and I took the code from a sample. The reason if filled in the variables at the beginning was to serve as a sample set of values, which I wanted the user to adjust.
Your explanation went over my head, as I am so new to javascript. Could you fix the code I submitted so it works properly and allows people to enter a decimal point on field 2 and a straight percentage value (like 30)?
Your explanation makes sense, but modifying the code with your fixes is beyond me, it is so easy to make mistakes with this.
I would be extrememly grateful if you could show me the whole solution.
AlanP - You should be aware that it is not really in your best interests that others do your all or most homework for you. Many people would regard that as cheating. Furthermore your teacher may gain a false and exaggerated idea of your programming capabilities and so not offer you the support you need. Also, if you hand in other people's work which you do not completely understand, then you will start to fall behind and your difficulties will increase. This is especially so if "Your explanation went over my head". That means that you are very much out of your depth.
To repeat:- 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++.
Hint: be aware that a large proportion of the code used with data which is entered by the user is validation of the inputs. Were it not for this the code would be little different from multiplying four fixed numbers. Again, be aware that form field values are strings unless/until converted to numbers by one of several methods, Number() being recommended. As it happens in this case (multiplication) automatic type conversion will apply - but do not rely on that!!! You still need to make the conversion for validation purposes.
If you want the user to enter a percentage value as 30 rather than .3, all you have to do is divide by 100 to get .3, add 1 to get 1.3 and then multiply the base value (say 10) by that (to give 13). But of course you must check that the value entered by the user is indeed a number such as 30 and not .3 as otherwise the answer is silly. So, for example, check that the percentage figure is either zero or greater than 1, and if not require it to be entered again. Zero is OK in the multiplication because 0/100 = 0 + 1 = 1.00.
To give you the flavour of how you could do this (but well beyond you at this stage):-
Code:
Enter the percentage <input type = "text" id = "percent" size = "3" onblur = "checkit()">
<script type = "text/javascript">
function checkit() {
var val = Number(document.getElementById("percent").value) || 0; // trap NaN entries by converting to 0
document.getElementById("percent").value = val; // write it back to the field
if ((val < 1) && (val !=0) || (val <0)) { // not negative, not a decimal less than 1
alert ("You must enter either 0 or a number 1 or greater"); // alerts are considered obsolete nowadays - you should use DOM methods to display the message
document.getElementById("percent").value = ""; // clear the field;
document.getElementById("percent").focus(); // and refocus on it
return false;
}
}
</script>
All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.
__________________
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.
No, it's not homework. I'm trying to help out a guy I built a website theme for. I don't do javascript calculators, so when he wanted one, I gave it a shot by looking up on javascript source. The solution I came up with does work, but only if you don't try and alter the hourly rate field, or put in a decimal point. So, I am just out of my element here, and I'm trying to give him a solution that will work.
Ideally, it would be nice if the visitor was able to enter a percentage in the markup percentage field, and in the hourly rate, they could enter a number with decimal place, like 10.25 / hour 11.75, whatever.
Like I said, this isn't homework, I'm just out of my element doing javascript calculators.
Here is the page on the website I built for him where I put in the bad version I cam up with. http://ironmanconsultants.com/?page_id=412
I dunno, Philip. The <iframe> with the calculator in it is 100% a clone of the code he showed here in the forum.
There's really not JavaScript in the rest of the site that isn't just some library pulled from somewhere. So it's not like he had to understand anything but HTML and CSS to get this far.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
I don't know how things work where you come from, but where I come from, it is considered rude to call someone a liar. I'm not in the habit of lying to people, nor was I in any way trying to pretend javascript was something I am well versed in.
Website design, graphics, page content and flow, and getting customers to buy whatever is is someone is trying to sell is what I do, and I do it quite well thank you very much.
What I don't do is insult perfect strangers who ask for help from me, especially when that person has not attempted to insult me.
Fair enough, if you say so. It seemed to me a very big contast between the expert coding of that page and the seemingly juvenile code offered in Post#1. It gave the impression of school homework to me (and to Old Pedant as well). Perhaps web site design competence does not include any knowledge of Javascript. I withdraw my comment.
__________________
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.
Perhaps web site design competence does not include any knowledge of Javascript.
It's not common in my experience to find web site designers without competence in JavaScript, but it does happen. The primary designer with the company I am primarily contracting to is a bit more competent than AlanP, from the evidence of this thread, but not very much more. If he didn't have tons of jQuery libraries to fall back on, he'd be pretty much lost. (The mildly funny part is that his assistant is much much more competent, but without the design skills, and the boss wants the designs done right, so...)
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
It's not common in my experience to find web site designers without competence in JavaScript, but it does happen.
One good example would be Google - from the look of the so called JavaScript they provide they don't employ any web site designers who are competent with JavaScript.