Need to add totals of select list, and subtract if taken away
Posted
by
jeremy
on Stack Overflow
See other posts from Stack Overflow
or by jeremy
Published on 2011-02-01T01:22:29Z
Indexed on
2011/02/01
23:25 UTC
Read the original article
Hit count: 399
jQuery
|calculation
This is the code I am using to calculate the sum of two values (example below)
http://www.healthybrighton.co.uk/wse/node/1841
This works to a degree. It will add the two together but only if #edit-submitted-test
is selected first, and even then it will show NaN until I select #edit-submitted-test-1
.
I want it to calculate the sum of the fields and show the amount live, i.e. the value of edit-submitted-test-1
will show 500
, then if i select another field it will update to 1000
. If i take one selection away it will then subtract it and will be back to 500
. Any ideas would be helpful thanks!
Drupal.behaviors.bookingForm = function (context) {
// some debugging here, remove when you're finished
console.log('[bookingForm] started.');
// get number of travelers and multiply it by 100
function recalculateTotal() {
var count = $('#edit-submitted-test').val();
count = parseFloat( count );
var cost = $('#edit-submitted-test-1').val();
cost = parseFloat( cost );
$('#edit-submitted-total').val( count + cost );
}
// run recalculateTotal every time user enters a new value
var fieldCount = $('#edit-submitted-test');
var fieldCount = $('#edit-submitted-test-1');
fieldCount.change( recalculateTotal );
// etc ...
};
EDIT
This is all working beautiful, however I now want to add all the values together, and automatically update a total cost field that is the sum of a the added field with code above and field with value passed from previous page.
I did this where accomcost is the field that is added together, but the total cost field does update, but not automatically, it is always one selection behind. i.e. If i select options and accomodation cost updates to £900, total cost remains empty. If i then change the selection and the accomodation updates to £300, the total cost updates to the previous selection of £900. Any help on this one Felix? ;) thanks.
var accomcost = $('#edit-submitted-accomodation-cost').val();
accomcost = accomcost ? parseFloat(accomcost) : 0;
var coursescost = $('#edit-submitted-courses-cost-2').val();
coursescost = coursescost ? parseFloat(coursescost) : 0;
$('#edit-submitted-accomodation-cost').val( w1 + w2 + w3 + w4 + w5 + w6 + w7 + w8 + w9 + w10 + w11 + w12 + w13 + w14 + w15 + w16 + w17 + w18 + w19 + w20 + w21 + w22 + w23 + w24 + w25 + w26 + w27 + w28 + w29 + w30 );
$('#edit-submitted-total-cost').val( accomcost + coursescost );
var fieldCount = $('#edit-submitted-accomodation-cost, #edit-submitted-courses-cost-2') .change( recalculateTotal );
© Stack Overflow or respective owner