0

This has been racking my brain all day, and I can't work out how to do it... can anyone help?

I want to use the jQuery Calculation plugin to perform a calculation from input boxes on my site...

For example:

Input boxes: Number of guests and Number of servings

100 or less guests: £180
+
£1 per each additional guest (101+)
+
£0.60 per each additional guest serving

Calculation: would be £180+(additional guests x £1)+(total guests x servings @ £0.60)

Example: 112 guests with 2 servings would be £180+£12+£67.20=£259.20

Can anyone help at all?

Thanks in advance

Manse
  • 37,765
  • 10
  • 83
  • 108
Craig Eves
  • 131
  • 2
  • 4
  • 11

2 Answers2

0

No need for a plugin - its simple maths :

$('#numguests,#numservings').change(function() {
    // get value of input - parse to int
    var numguests = parseInt($('#numguests').val(), 10); 
    // base guest price
    var guestprice = 180; 
    if (numguests > 100) {
        // add cost of extra guests
        guestprice = guestprice + (numguests - 100); 
    }
    var servingsprice = 0;
    // get value of input - parse to int
    var numservings = parseInt($('#numservings').val(), 10); 
    if (numservings > 1) {
        // add cost of extra servings
        servingsprice = numguests * 0.60; 
    }
    // round to 2 places and output
    $('#total').html(parseFloat(guestprice + servingsprice).toFixed(2)); 
});​

Working example here

Manse
  • 37,765
  • 10
  • 83
  • 108
  • Thanks for that. Works like a charm on jsfiddle but cant get it working here: http://mooscandybar.co.uk/vintage-sweet-shop-dev.php – Craig Eves May 30 '12 at 15:44
  • sorry about not accepting answers. I have done so now. Also - I kind of have it working now at http://jsfiddle.net/craigeves/QcgRs/12/ and http://mooscandybar.co.uk/test.html but it wont work out the servings price beyond 2 servings. do you know why? – Craig Eves May 30 '12 at 22:30
  • @CraigEves: `servingsprice = numguests * 0.60` should be `servingsprice = numguests * 0.60 * (numservings-1)` – forsvarir May 31 '12 at 07:15
0

Final code:

<script type="text/javascript">



$(document).ready(function() {





$('#numguests,#numservings').change(function() {
var numguests = parseInt($('#numguests').val(), 10);
var guestprice = 180;
if (numguests > 100) {
guestprice = guestprice + (numguests - 100);
}
var servingsprice = 0;
var numservings = parseInt($('#numservings').val(), 10);
if (numservings > 1) {
servingsprice = numguests * 0.60 * (numservings-1);
}
$('#total').html(parseFloat(guestprice + servingsprice).toFixed(2));
});

});
</script>


<div id="calculator">
<p><strong>Use our Cost Calculator to work out a price:</strong></p>
<p>Number of guests <input id="numguests" value="100"><br>
Number of 4oz servings per guest<input id="numservings" value="1"><br>
Total price : &amp;<span id="total"></span></p>
</div>




</div>
Craig Eves
  • 131
  • 2
  • 4
  • 11