【发布时间】:2017-06-13 12:50:38
【问题描述】:
我刚刚开始学习 JavaScript,但在尝试让多个复选框工作时遇到了问题。
我正在尝试根据选中的选项计算产品成本。但是,我的脚本会自动假设所有框都已被选中。
这段代码有什么问题?对不起,如果这是一个基本问题,但我已经敲了几个小时了。
function cal() {
var selectionOne = 0;
var selectionTwo = 0;
var selectionThree = 0;
var total = 0;
if (document.getElementById("1").checked = true ){
selectionOne = 25;
}
if (document.getElementById("2").checked = true ){
selectionTwo = 50;
}
if (document.getElementById("3").checked = true ){
selectionThree = 100;
}
total = selectionOne + selectionTwo + selectionThree;
alert ("Your total is £" + total);
}
HTML
<html>
<head>
<title>Basic Pricing Script</title>
</head>
<body>
<script src="script.js"></script>
<p>Please select which options you want from the list</p>
<form name="priceoptions">
<input type="checkbox" id="1" name="big" value="big"> Big Prints<br>
<input type="checkbox" id="2" name="medium" value="medium" > Medium Prints<br>
<input type="checkbox" id="3" name="small" value="small" > Small Prints<br>
<input type="submit" id="button" value="Submit" onclick="cal()">
</form>
</body>
</html>
【问题讨论】:
-
在“if”语句中,您需要两个相等的符号来比较是否相等,而不仅仅是一个。
document.getElementById("1").checked == true. -
不需要
== true部分。而这一切都可以浓缩。看看我的回答
标签: javascript html forms checkbox input