【发布时间】:2021-03-07 23:09:59
【问题描述】:
所以我的代码背后的基本思想是这样的。
有一个可供选择的 7 个复选框和一个按钮,单击时应该会处理结果。
如果选中了两个框,则该函数应打印选择,如果选中的框数小于或大于 2,则应显示显示错误消息的警报。
为了跟踪复选框的数量,我运行了一个等于复选框数量的循环,并且每次array[index] == true,该给定复选框的值都应该添加到一个名为 selections 的数组中。
我的代码似乎无法将元素添加到数组选择中,我不明白为什么。
谁能帮我解释一下?
<fieldset>
<legend>Side Dishes</legend>
<h3>Pick two side dishes</h3>
<input type="checkbox" name="sides" id="1" value="French Fries">French Fries<br />
<input type="checkbox" name="sides" id="2" value="Baked Potato">Baked Potato<br />
<input type="checkbox" name="sides" id="3" value="Cole Slaw">Cole Slaw<br />
<input type="checkbox" name="sides" id="4" value="Garden Salad">Garden Salad<br />
<input type="checkbox" name="sides" id="5" value="Mixed Vegetables">Mix
Vegetables<br />
<input type="checkbox" name="sides" id="6" value="Macaroni and Cheese">Macaroni
and Cheese<br />
<input type="checkbox" name="sides" id="7" value="Applesauce">Applesauce<br />
<input type ="button" value = "Enter my side dish selections" id="sideselect"/>
</fieldset>
document.querySelector("#sideselect").addEventListener("click", validateSelection);
function validateSelection() {
//Creates a list of check boxes to count true or false.
var checkedSides = document.getElementsByName("sides");
//Array to hold selected check boxes.
var selections = [];
console.log(checkedSides);
console.log(checkedSides[1].value);
for (var j = 0; j < checkedSides.length; j++) {
//Inserts selected items into selections.
if (checkedSides[j].check === true) {
selections.push(checkedSides[j].value);
}
}
console.log(selections);
//Prints the first and second selected side to output if exactly 2 sides are selected.
if (selections.length === 2) {
document.querySelector("#side_one").textContent = selections[0];
document.querySelector("#side_two").textContent = selections[1];
//Tells the user they have selected too few items and clears selections.
} else if (selections.length < 2) {
alert("Please select at least 2 sides.");
selections = [];
//Tells the user they have selected too many items and clears selections.
} else if (selections.length > 2) {
alert("Order is limited to 2 sides. Please adjust your selection.");
selections = [];
}
}
【问题讨论】:
-
checkedSides[j].check === true应该是checkedSides[j].checked。我建议你改用 TypeScript 来捕捉这些错误。 -
我建议了解 DOM 元素及其属性比学习 TypeScript 更有价值——当然,TypeScript 可能有助于避免这些简单的错误——但是,你学到了什么?什么都没有
-
非常复杂的表单编码方式......
-
@Bravo 随心所欲地学习 DOM 元素属性并不是很好地利用程序员的时间。使用 TypeScript 之类的语言和 IDE 会在提示时为您列出正确的属性(IntelliSense、代码完成等)是一种快乐的媒介。
-
@Dai - 我们的意见不同:p
标签: javascript html arrays loops push