设置和添加数组值javascript时出现问题

Trouble setting and adding array values javascript

本文关键字:问题 javascript 添加 数组 设置      更新时间:2023-09-26

我想给每个复选框一个整数值,然后如果复选框被选中,则添加值并在ID为"options"的文本框中显示总数。到目前为止,代码还没有将值发送到所需的位置。任何关于如何改进代码的说明都会有所帮助。非常感谢。

<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
    var form = document.getElementById("registration"),
        inputs = form.getElementsByTagName("input"),
        result = 0;
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type === "checkbox" && inputs[i].checked) {
            result += inputs[i].value;
            document.getElementById("options").value = result;
        }
    }
}
getOptions();
</script>

您可能需要将onchange事件处理程序附加到复选框中,如下所示。在将inputs[i].value添加到result之前,应该使用parseFloat()将其解析为一个数字。

var form = document.getElementById("registration"),
    inputs = form.getElementsByTagName("input");
function getOptions() {
    var result = 0;
    for (var i = 0, len = inputs.length; i < len; i++) {
        if (inputs[i].type === "checkbox" && inputs[i].checked) {
            result += parseFloat(inputs[i].value);
        }
    }
    document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
    if (inputs[i].type === "checkbox") {
        inputs[i].onchange = function () {
            getOptions();
        }
    }
}
getOptions();

JSFiddle