设置和添加数组值时遇到问题 javascript
Trouble setting and adding array values javascript
我想给每个复选框一个整数值,然后如果复选框被选中,则添加值并在 ID="options" 的文本框中显示总数。到目前为止,代码没有向所需位置发送值。任何关于如何改进代码的说明都会有所帮助。谢谢。
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ()
<input name="opt2" value="10" type="checkbox"> Lunch ()
<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 event handlers to the checkboxes as shown below. And you should parse inputs[i].value
to a number using parseFloat(),然后再将其添加到 result
。
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();
我想给每个复选框一个整数值,然后如果复选框被选中,则添加值并在 ID="options" 的文本框中显示总数。到目前为止,代码没有向所需位置发送值。任何关于如何改进代码的说明都会有所帮助。谢谢。
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ()
<input name="opt2" value="10" type="checkbox"> Lunch ()
<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 event handlers to the checkboxes as shown below. And you should parse inputs[i].value
to a number using parseFloat(),然后再将其添加到 result
。
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();