我有一个脚本,它根据表单添加所有项目,然后减去这些项目中最小的一项以创建新的总计。我希望能够以表格形式返回结果。
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种不同的总数。我想通过表格提交的所有内容都是最终的总数。表单功能齐全,效果很好,我只想将这些结果包含在表单中。
&安培;以下是其中的链接:
答案 0 :(得分: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”的值。
当涉及金钱时,在现实生活中永远不要(特别是TRUST)这样做;任何人都可以发布任何他们想要的东西!!