Hello,
i have a simple form that calculates the total of some checkboxes which works fine. Now, I need to offer a flat rate when 2 or more boxes are checked.
Example: 1 box = 100, 2 boxes or more = 175.
Finally, certain checkboxes must be exempt from the discount.
I am new to JS and just to get the form i currently have to work, took me forever, so please be gentle!
Here is my code:
<script type="text/javascript">
function calculate() {
var elems = document.forms['form1'].elements;
var total = 0;
for(var i=0;i<elems.length;i++) {
if (elems[i].checked) {total += +(elems[i].value);}
}
elems['total'].value = total;
}
</script>
Here's a new function calculate that will change total's value to whatever you want if two checkboxes get checked:
Code:
function calculate() {
var elems = document.forms['form1'].elements;
var total = 0;
var c = 0
for(var i=0;i<elems.length;i++)
{
if (elems[i].checked)
{
c++;
// if both flat rate boxes are checked, apply your flat rate value to total
if(c >= 2)
{
total = 175; // whatever your flat rate is
}
// else just apply checkbox values to total
else
{
total += +(elems[i].value);
}
}
}
elems['total'].value = total;
}
Also, notice how much more readable the code is now that I've nested everything.
hey,
thanks that works great.
How about exempting certain boxes from the flat rate? In other words, certain checked boxes would always add to the total and be exempt from the function.
thanks again!
Then just change your if statement, that looks for 2 or more checkboxes, to check that the inputs with id's are NOT checked, like:
Code:
if(c >= 2 && (!document.getElementById('cb1').checked) )
{
total = 175; // whatever your flat rate is
}
// else just apply checkbox values to total
else
{
total += +(elems[i].value);
}
No problem: but, in the future, don't be afraid to show your code or anything like that. I may have been able to spot where you went wrong and it could be working. Feel free to do so if you want to get it working still.
Bookmarks