我的代码如下,我在这里使用数组。我试图打印"无"当没有选择任何选项时的值,但是当我提交表单时,我选择了几个复选框;它仍然说"无"。当我选择不选择其中一个选项时,如果没有else if条件,那么我得不到任何结果。
我不应该创造一个"无"输入功能的选项。
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
} else if (!extras[count].checked) {
array = ["None"];
}
}
alert("(Including extras: " + array + ")");
}
&#13;
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>
&#13;
答案 0 :(得分:1)
问题是,每当有一个空的复选框时,您就会用array
替换["None"]
,而不是当复选框的所有为空时
最简单的解决方法是在循环后检查array
是否为空,例如:
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
这是一个工作片段:
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
alert("(Including extras: " + array + ")");
}
&#13;
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>
&#13;