选择特定的值组合时,我试图限制复选框的选项。
我有一个名称为toneCapArray
的检查组,当选择value="bp"
和value="master-tone"
时,我想限制该复选框。这些值在最后两个选择框中指定。
我刚学习JS几个月,就遇到了障碍。选择这两个值时,我无法运行该函数。
checkboxlimit(toneCapArray, 1);
函数直接在函数定义下运行时,它将起作用。
但是,当我通过查看两个函数是否都正确时来调用该函数:(item.value === "bp" && item.value === "master-tone")
它不起作用,并且我没有收到任何错误或任何有助于调试它的信息。
function masterCheckboxLimit() {
//set up the locations:
const toneCapArray = document.getElementsByName("addon-3987-tone-cap-2[]");
var select = document.querySelectorAll("select");
//limit the checkboxes:
function checkboxlimit(checkgroup, limit) {
for (var i = 0; i < checkgroup.length; i++) {
checkgroup[i].addEventListener("click", function () {
var checkedcount = 0;
for (var i = 0; i < checkgroup.length; i++) {
checkedcount += checkgroup[i].checked ? 1 : 0;
if (checkedcount > limit) {
window.alert("You can only select a maximum of " + limit + " tone caps");
this.checked = false;
}
}
});
}
}
//select the select boxes and add a change event listener
select.forEach((item) => {
item.addEventListener("change", (e) => {
if (item.value === "bp" && item.value === "master-tone") {
checkboxlimit(toneCapArray, 1); //when these two are selected, I want this function to run.
}
});
});
}
masterCheckboxLimit();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Product Options:</h1>
<p>
<select name="pickup_location" id="" label="">
<option value="">Select an Option</option>
<option value="complete_set">Complete Set</option>
<option value="neck">Neck</option>
<option value="bridge">Bridge</option>
</select>
</p>
<p>
<select name="pickup_color" id="" label="">
<option value="">Select an Option</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</p>
<p>
<select name="tone_pot_1" id="" label="">
<option value="">Select an Option</option>
<option value="neck_middle_tone">Neck and Middle Tone</option>
<option value="master-tone">Master Tone</option>
</select>
</p>
<p>
<select name="tone_pot_2" id="" label="">
<option value="">Select an Option</option>
<option value="bp">Blender Pot</option>
<option value="bridge-tone">Bridge Tone</option>
</select>
</p>
<h2>Add Ons:</h2>
<p><input type="checkbox" id="1" name="addon-3987-tone-cap-2[]" value="Cap 1" label="Cap 1" /><label for="1">Tone Cap 1</label></p>
<p><input type="checkbox" id="2" name="addon-3987-tone-cap-2[]" value="Cap 2" label="Cap 2" /><label for="2">Tone Cap 2</label></p>
<p><input type="checkbox" id="3" name="addon-3987-tone-cap-2[]" value="Cap 3" label="Cap 3" /><label for="3">Tone Cap 3</label></p>
</body>
</html>
我的代码中有什么明显的地方吗?
我在您的代码中看到2个问题
if (item.value === "bp" && item.value === "master-tone")
因为"bp" !== "master-tone"
item.value不能两者都相等(除非那里有骇人的吸气剂)