jQuery: Calculate total price amount on Multiple Checkbox & Radio button selection

Scenario:

I have different checkboxes and radio buttons. The checkboxes and radio buttons have some price value associated with them. Upon checking them I have to calculate the total price and display it in a textbox.

Solution:

We’ll use jQuery for this scenario.

Here’s an example HTML to create checkbox and radio buttons. Checkboxes are made to be multiple selected. Radio buttons are made to be single selected.


<p>
	<strong>Food</strong> <br />		
	<input class="my-activity" type="checkbox" name="activity['food']['breakfast']" value="5"> Breakfast (US$ 5)<br/>
	<input class="my-activity" type="checkbox" name="activity['food']['lunch']" value="10"> Lunch (US$ 10)<br/>
	<input class="my-activity" type="checkbox" name="activity['food']['dinner']" value="15"> Dinner (US$ 15)<br/>		
</p> 
<p>
	<strong>Entertainment</strong> <br />		
	<input class="my-activity" type="radio" name="activity['entertainment']" value="5"> Swimming (US$ 5)<br/>
	<input class="my-activity" type="radio" name="activity['entertainment']" value="10"> Movie (US$ 10)<br/>
	<input class="my-activity" type="radio" name="activity['entertainment']" value="15"> Sight Seeing (US$ 15)<br/>		
</p>
<p>
	<strong>Amount (US$)</strong>: <input type="text" name="amount" id="amount" />
</p>

Here’s jQuery code to calculate and show total amount based on the selection. “my-activity” is the class name given to the checkboxes and radio buttons.


<script type="text/javascript">
$(document).ready(function() {		
	$(".my-activity").click(function(event) {
		var total = 0;
		$(".my-activity:checked").each(function() {
			total += parseInt($(this).val());
		});
		
		if (total == 0) {
			$('#amount').val('');
		} else {				
			$('#amount').val(total);
		}
	});
});	
</script>

VIEW DEMO

Form action in the above demo is test.php. I have just printed the post data in it.
Here is the code present in test.php:


<?php 
echo "<pre>"; 
	print_r($_POST); 
echo "</pre>"; 
?>
<p>
	<a href="#" onClick="window.history.go(-1); return false;">Go Back</a> 
</p>

VIEW DEMO

Hope this helps. Thanks.