Reputation: 484
Ok, I've got a unique one here and I've been searching all over the googles and stackoverflow and found nothing that matches exactly what I need. Here's what I've got.
I have three checkboxes in a form, these represent 3 different "events". What I need is that if a person checks any ONE checkbox the total is $30. If they check any two of the boxes the total is $40 and if they check all 3 the total is $50. Since they may check any one, two, or all 3 boxes I can't have the prices set statically in the value. I need something that say roughly "if 1 box selected, price is $30, if 2 boxes selected, price is $40, if 3 boxes selected, price is $50".
I'm good with PHP and mySQL and I know I could accomplish this with PHP but I would have to submit the form first before the price would update, this is why I need javascript to update the pricing as the user checks/unchecks boxes. Thanks for all responses!
Upvotes: 0
Views: 538
Reputation: 78520
well... it's been answered by a couple people already, but I like my way... so I'll post it.
pure javascript and DOM, so no need to fiddle with libraries.
Upvotes: 0
Reputation: 2778
Here's something that should get you started - this is all based on the assumption that there are only 3 checkboxes on your whole page and that you're interested in all of them - you'll want to make a method like this respond to your checkbox elements' onclick events - I've found that to be more reliable than onchange.
function updateTotal() {
var checked = 0;
var inputs = document.getElementsByTagName("INPUT");
for (var i = 0; i < inputs.length; i++) {
if (/checkbox/i.test(inputs[i].type) && inputs[i].checked) {
checked++;
}
}
var priceInDollars = 0;
switch (checked) {
case 1:
priceInDollars = 30;
break;
case 2:
priceInDollars = 40;
break;
case 3:
priceInDollars = 50;
break;
}
var priceElement = document.getElementById("the id of your element where you'll print the price");
priceElement.innerText = "$".concat(priceInDollars.toString());
}
EDIT:
I'm not a JQuery master yet - I like the JQuery answer for retrieving the count much better than mine - much cleaner...
Upvotes: 2
Reputation: 5659
Use:
var cont=$('#yourContainerId'),nbSelected=$(':checkbox:checked',cont).length,result=0;
if(nbSelected==1) result=30;
else if(nbSelected==2) result=40;
else if(nbSelected==3) result=50;
return result;
Upvotes: 3