开发者

Calculating Values loaded in via jquery

A continuation from a solved case with a new problem. The following code calculates values that are loaded in via ajax from another script. A series of options in another form determine what information is loaded in and therefore what the final calculations are.

The problem is that once you have loaded in all the available options you cannot then load them out and the script that adds up all the field totals does in fact fail at this point. So for example if you load in 2 options it will had up the totals. Load in a third and it will add up the total of all 3. Take one option out and the script then fails. I believe it is something to do with the way the script fetches the product ids — var productIds = {};

Any help would be appreciated

Here is the code

var productIds = {};

function product_totals(id) {
    productIds[id] = true; // store all id's as the totals are calculated
    var quantity = $c('product_quantity_' + id).value;
    var price = $c('product_price_' + id).value;
    var duration = $c('product_duration_' + id).value;
    var dives = $c('product_dives_' + id).value;
    var hire = $c('product_hire_' + id).value;
    Number($c('product_price_total_' + id).value = price * quantity);
    Number($c('product_duration_total_' + id).value = duration * quantity);
    Number($c('product_dives_total_' + id).value = dives * quantity);
    Number($c('product_hire_total_' + id).value = hire * quantity);

    function $c(id) {
        return document.getElementById(id);
    }

    var totalPriceTotal = 0;
    var totalDurationTotal = 0;
    var totalDivesTotal = 0;
    var totalHireTotal = 0;
    for (var id in productIds) {
        // multiply by 1 to make sure it's a number
        totalPriceTotal += $c('product_price_total_' + id).value * 1;
        totalDurationTotal += $c('product_duration_total_' + id).value * 1;
        totalDivesTotal += $c('product_dives_total_' + id).value * 1;
        totalHireTotal += $c('product_hire_total_' + id).value * 1;
    }
    $c('GT_total_price').value = totalPriceTotal;
    $c('GT_total_duration').value = totalDur开发者_如何学PythonationTotal;
    $c('GT_total_dives').value = totalDivesTotal;
    $c('GT_total_hire').value = totalHireTotal;

    function $c(id) {
        return document.getElementById(id);
    }
}

working sample at http://www.divethegap.com/update/diving-trips/adventure-training/#level_01 (click on beginners) Many Thanks


If i do understand, what your trying to achieve is to stack up a collection of ids in an array from which you can remove items so you can calculate only selected options. I would declare var productIds = []; and add ids in it using productIds.push(id). When you remove an option the you could just use productids.splice(indexofId, 1);. When you recalcultate you would just have the ids you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜