簡體   English   中英

如何通過表單提交JavaScript Equation的值?

[英]How do I make the Values of JavaScript Equation Submit through a form?

我有一個腳本,可以根據表單添加所有項目,然后減去這些項目中的最小項目以創建新的總計。 我希望能夠以表格形式返回結果。

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/

要回答您的評論(和問題):

在您的表單中,添加一個字段<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”的值。

當涉及到金錢時,在現實生活中永遠做不到(尤其是信任)。 任何人都可以張貼他們想要的任何東西!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM