jQuery: Calculate total price amount on selecting Select & Multi-select box

Scenario:

I have different select box and multiple select boxes. The select dropdown and multi select boxes have some price value associated with them. Upon selecting 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 select and multi-select boxes. Multiple values can be selected from multi-select box. Single value can be selected from the select box (dropdown).


<p>
	<strong>Food</strong> <br />
	<select class="myactivity" name="activity['food'][]" multiple="multiple">			
		<option value="5">Breakfast (US$ 5)</option>
		<option value="10">Lunch (US$ 10)</option>
		<option value="15">Dinner (US$ 15)</option>			
	</select>		
</p> 
<p>
	<strong>Entertainment</strong> <br />
	<select class="myactivity" name="activity['entertainment']">
		<option value="0">Please Select</option>
		<option value="5">Swimming (US$ 5)</option>
		<option value="10">Movie (US$ 10)</option>
		<option value="15">Sight Seeing (US$ 15)</option>
	</select>		
</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.