Reputation: 1
Im a Javascript beginner, but I have built a simple Cost Estimator for my site using Javascript math functions.
function calc(form) {
a = eval(form.a.value)
b = eval(form.b.value)
c = eval(form.c.value)
x = a*(b+c)
form.ans.value = parseFloat(x).toFixed(2);
}
The form is simple:
<form name="formx">
<label for="a">Number of Units :</label>
<input type="number" size=3 value=0 name="a">
<label for="b">Price per Unit :</label>
<select name="b">
<option value="0.04">0.04</option>
<option value="0.05">0.05</option>
<option value="0.06">0.06</option>
</select>
<label for="c">Tick if Urgent</label>
<input name="c" type="checkbox" value="0.01" />
<input class="button" type="button" value=" CALCULATE " onClick="calc(this.form)">
<label for="ans">Total Cost :</label>
<input value=" £ " name="ans" size=6>
</form>
The "c" value, for Urgent Service, is 0.01, BUT it needs to be added ONLY when the checkbox is checked, otherwise its value MUST be 0. But I can't seem to figure it out, because it is always adding "c" value as 0.01, checked or unchecked.
Please help
Upvotes: 0
Views: 1662
Reputation: 8976
Try this-
function calc(form) {
var a = parseFloat(form.a.value)
var b = parseFloat(form.b.value)
var c = (form.c.checked) ? parseFloat(form.c.value) : 0;
var x=a*(b+c)
form.ans.value=parseFloat(x).toFixed(2);
}
Note -
eval
is evilFrom Douglas Crockford's website - JavaScript Code conventions
The eval function is the most misused feature of JavaScript. Avoid it.
eval has aliases. Do not use the Function constructor. Do not pass strings to setTimeout or setInterval.
Also, read this-
Upvotes: 4
Reputation: 909
Consider using Radio Buttons instead of Checkboxes. Then you can have multiple values linked to a single object. See http://www.w3schools.com/html/html_forms.asp for the exact diffrences
Upvotes: 0