# Checkbox Discount Selection

Hi, Im ‘trying’ to write a checkbox type calculator. How can I do something along the lines of,

If 5 checkboxes are checked, apply a 2% discount to the total.

I am by no means an expert in javascript. I found a bit of jQuery

``````            \$(document).ready(function() {
var total = 0;

function calcTotal() {
\$("input:checked").each(function() {
var value = \$(this).attr("value");
total += parseFloat(value);
});
}

calcTotal();

total = 0;
calcTotal();
\$("#total").val(\$.format('{a:.2f}', { a:total }));
});
});
``````

The discounts are 2% off the total per each additional item selected. Eg if 6 items are selected then its 2% off the total, 7 items then its 4% off etc … max of 15 selectable

Many thanks

Okay this is what it looks like:

Total: £<input id=“total” type=“text” />

<input type=“checkbox” name=“Item1” id=“Item1” value=“1.00” />
<input type=“checkbox” name=“Item2” id=“Item2” value=“1.00” />
<input type=“checkbox” name=“Item3” id=“Item3” value=“1.00” />
etc…

<script type=“text/javascript” src=“…/scripts/jquery-latest.js”></script>
<script type=“text/javascript” src=“…/scripts/jquery.strings.js”></script>
<script type=“text/javascript”>
var total = 0;

``````			function calcTotal() {
\$("input:checked").each(function() {
var value = \$(this).attr("value");
total += parseFloat(value);
});
}

calcTotal();

total = 0;
calcTotal();
\$("#total").val(\$.format('{a:.2f}', { a:total }));
});
});
``````

</script>

<script type=“text/javascript”>

var chkBoxes = new Array();

var inputElems = document.getElementsByTagName(“input”);
for(var i=0; i < inputElems.length; i++) {
if(inputElems[i].type == “checkbox”) chkBoxes.push(inputElems[i]);
}
}
function calcTotal() {
var numSelected = 0;
var total = 0;
for(var i=0; i < chkBoxes.length; i++) {
if(chkBoxes[i].checked) {
numSelected++;
total += parseFloat(chkBoxes[i].value);
}
}
if(numSelected >=5) total = total*0.98;
}
</script>

Many thanks

Smething along the lines of this demo. You can add the extra discount calcs.

``````
<script type="text/javascript">

var chkBoxes = new Array();

var inputElems = document.getElementsByTagName("input");
for(var i=0; i < inputElems.length; i++) {
if(inputElems[i].type == "checkbox")   chkBoxes.push(inputElems[i]);
}
}
function calcTotal() {
var numSelected = 0;
var total = 0;
for(var i=0; i < chkBoxes.length; i++) {
if(chkBoxes[i].checked) {
numSelected++;
total += parseFloat(chkBoxes[i].value);
}
}
if(numSelected >=5) total = total*0.98;