如何定义一个变量并在隐藏的输入字段中调用它

How do I define a variable and call it in a hidden input field?

本文关键字:隐藏 输入 字段 调用 变量 定义 何定义 一个      更新时间:2023-09-26

我有一个javascript代码可以进行一些数学运算,我需要能够提取最终结果并将其包含在表单中。为此,我只想使用<input type="hidden" name="new total">。我想从字段"新总计"中获取结果。你可以在这里看到我的javascript代码。http://jsfiddle.net/danielrbuchanan/yjrTZ/5/

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>';
}

这看起来很简单,出于某种原因,我对如何做到这一点一无所知。

我认为你想要的是用你的变量设置一个输入值,所以我认为它应该是这样的:

Javascript:

document.getElementById("newTotal").value = your_new_total;

HTML:

<form>
    <input id='newTotal' type='hidden' name='NewTotal' value='' />
</form>

希望这能有所帮助。

<input type="hidden" id="new_total" name="new_total">
<!-- no spaces in name and id -->

将此代码放在calculateSectedDues功能的末尾

document.getElementById('new_total').value = withDiscount

您有几个选项。

选项1:jQuery

添加一个可见的div,无论你想怎么做。将onChange((事件绑定到驱动计算的输入字段。

<div id="finalValue"></div>
<script language="javascript">
$(function() {
    $("form input").change(function() {
        calculateSectedDues($("#checkboxid"), $("#amountid").val());
    });
});
</script>

在calculateSectedDues((函数中,将其添加到末尾:

$("#finalValue").html("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");

选项2:无jQuery

<div id="finalValue"></div>
<script language="javascript">
function bindEvent() {
    calculateSectedDues(document.getElementById("checkboxid"), document.getElementById("amountid").value);
}
window.onload = function()
{
    var elJ = document.getElementsByTagName("input");
    for (var i=0;i<elJ.length;i++) {
        elJ[i].addEventListener('change',bindEvent,false);
    }
}
</script>

在calculateSectedDues((函数中,将其添加到末尾:

document.getElementById("finalValue").InnerHtml("Total: $" + total + "<br />Discount: " + discountAmount + "<br />New Total: " + withDiscount + "<br />");

这就是你想要的吗?

您还应该记住在服务器端进行计算,而不是依赖JavaScript为您进行计算。这只是简单地通知用户他们手头有什么。否则,如果您使用隐藏的合计字段,则可以很容易地进行前端破解。