0

我有一个脚本,它根据表单添加所有项目,然后减去这些项目中最小的一个以创建一个新的总数。我希望能够以表格的形式返回结果。

JavaScript:

var prices = [];

function remove(arr,itm){
    var indx = arr.indexOf(itm);
    if (indx !== -1){
        arr.splice(indx,1);
    }
}

function calculateSectedDues(checkbox, amount) {
    if (checkbox.checked === true) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    var total = 0;
    for (var i = 0, len = prices.length; i < len; i++)
        total += prices[i];

    var min = prices.slice().sort(function(a,b){return a-b})[0];
    if(typeof min === 'undefined') min = 0;

    var withDiscount = total - min;
    var discountAmount = withDiscount - total;

    //document.grad_enroll_form.total.value = total;
    document.querySelector("#value").innerHTML = "Total: $"+total+'<br>';
    document.querySelector("#value").innerHTML += "Discount: $"+discountAmount+'<br>';
    document.querySelector("#value").innerHTML += "New total: $"+withDiscount+'<br>';
}

HTML:

<label><input type="checkbox" onclick="calculateSectedDues(this,5)" name="Scarf"> <span>Scarf</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,10)" name="Hat"> <span>Hat</span><label><br>
<label><input type="checkbox" onclick="calculateSectedDues(this,20)" name="Jacket"> <span>Jacket</span><label><br>

<span id="value">Total: $0<br>Discount: $0<br>New total: $0</span>

您会注意到有 3 个不同的总数。我想通过表格提交的只是最终总数。该表单功能齐全且效果很好,我只想将这些结果包含在表单中。

&这里是它的链接:

http://jsfiddle.net/danielrbuchanan/yjrTZ/5/

4

1 回答 1

0

要回答您的评论(和问题):

在您的表单中,添加一个字段<input type="hidden" name="finalTotal">
然后让您的函数calculateSectedDues以:document.getElementById('finalTotal').value=withDiscount;

它可能看起来像(稍微重构一下,看看我对“价值”做了什么):

function calculateSectedDues(checkbox, amount) {
    if (checkbox.checked) {
        prices.push(amount);
    } else {
        remove(prices, amount);
    }

    var total = 0, i = 0, len = prices.length;
    for (; i < len; i++) {
        total += prices[i];
    }

    var min = prices.slice().sort(function(a,b){return a-b})[0];
    if(typeof min === 'undefined') min = 0;

    var withDiscount = total - min;
    var discountAmount = withDiscount - total;

    //document.grad_enroll_form.total.value = total;
    document.getElementById('value').innerHTML = "Total: $"+total+'<br>'
                                               + "Discount: $"+discountAmount+'<br>'
                                               + "New total: $"+withDiscount+'<br>';
    //set hidden input value
    document.getElementById('finalTotal').value = withDiscount; 
}

提交此表单后,服务器收到的后期数据将包含一个名为“finalTotal”的值,其中包含“withDiscount”的值。

当涉及金钱时,千万不要在现实生活中这样做(尤其是信任);任何人都可以发布他们想要的任何内容!

于 2013-04-18T20:50:13.893 回答