Forum Moderators: open
Could anyone kindly show this js newbie the best way to encode a checkbox form with the following individually pre-defined values to calculate a total? I could do it if the values were static (see //comments) but I'm stumped - and a little daunted as maths is not my best subject.
(box1) ($1.50 per punnet) //what if someone orders 3 punnets?
(box2) ($5.99 per kg) //or 2 and 1/2 kilos?
(box3) ($4.99 per kg) //what if they want 4 kilos?
(box4) ($17.99 per kg) //or only half a kilo?
(box5) ($3.50 for 2) //or 3, or 4?
(TOT) ($ . )
Basically I'd want the checkboxes to calculate into the $total box and update after each checkbox is ticked/cleared.
I'm in way too deep as I speak (in terms of work commitments x study workload) so would deeply appreciate the expertise I've seen displayed by some of the well-oiled here at webmasterworld.
Considering this is my first post I feel greedy, but I'm really leaning on you guys for help.
Thank you kindly for any help that may be offered.
antWong
<INPUT TYPE="checkbox" NAME="a" value="1.5" onclick="cal(this)">
Since "this" refers to the current object, the single text box, this will ignore the other items in the form. Being it's a checkbox (as opposed to radio) it will only send that value to the calculation function.
<input type="checkbox" name="a" id="a" value="1.5" onclick="cal(this.form)">
Refers to the entire form, so you can calculate all items in the form.
Can't map it ALL out to you, but
<form method="post" onSubmit="return calculate(this);">
Which does the same thing, but we're referring to the form. If the form returns false, it won't submit when using a submit button; if Javascript is disabled, you still get your order.
calculate would do something like
function calculate(form) { // <-- See? Form object is the parameter
var sub=0;
var tot=0;
var calcFields = new Array('field1','field2'.....);
var quanFields = new Array('q1','q2'.....);
for i (0..calcFields) {
sub=0; // to avoid it cqarrying values from previous
var ck = getElementById(calcFields[i]);
if (ck.checked) {
sub = document.getElementById(quanFields[i]) * ck;
tot += sub;
}
}
document.getElementById('total').value=tot;
if (errors) { alert('handle your errors here too'); }
else { form.submit(); } // Let JS handle it
}
return false;
Note I added id to your checkbox, it's a Good Idea to access your form elements by ID.
There's more, like correctly outputting decimal numbers and addressing problems if it concatenates as a string instead of adding a number, but that's the groundwork. :-)