javascript - 获取选中的复选框
问题描述
该代码假设将浇头中的物品分为肉和无肉。然后我计划获取我选择的所有配料的名称。我的问题是,当我执行 console.log(chosen_toppings) 时,我得到一个未定义的输出。但我需要得到我选择的浇头。有人可以帮助解决这个问题。
代码:
for (let i = toppings.length - 1; i >= 0; i--) {
var topp_withmeat = document.getElementById("meats");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name ='order_topping';
var type = toppings[i].is_meat;
//checks if the topping is a meat product
if (type == 1) {
var topping_meat = toppings[i].topping;
console.log(topping_meat);
checkbox.value = topping_meat;
topp_withmeat.appendChild(checkbox);
topp_withmeat.appendChild(document.createTextNode(topping_meat));
}
}
//goes through the topping list
for (let i = toppings.length - 1; i >= 0; i--) {
var topp_withoutmeat = document.getElementById("meatlesses");
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name ='order_topping';
var type = toppings[i].is_meat;
//checks if the topping is a meatless product
if (type == 0) {
var topping_meatless = toppings[i].topping;
checkbox.value = topping_meatless;
topp_withoutmeat.appendChild(checkbox);
topp_withoutmeat.appendChild(document.createTextNode(topping_meatless));
}
}
let orderButton = document.querySelector(".submitbutton").addEventListener("click", function(event) {
//gets the size
var chosen_size = document.querySelector('input[name="size"]:checked').value;
console.log(chosen_size);
//gets the toppings
var chosen_toppings = document.querySelectorAll('input[name="order_topping"]:checked').value;
console.log(chosen_toppings);
//gets the user
var currentUser = document.getElementById("username-fillin2").innerHTML;
console.log(currentUser);
});
谢谢
解决方案
在这里,使用一个map
和join
const getChosenToppings = () => {
return Array.from(document.querySelectorAll('input[type="checkbox"]:checked.topping')).map(({ value }) => value).join();
};
document.querySelector('button').addEventListener('click', () => {
console.log(getChosenToppings());
})
<input type="checkbox" class="topping" value="Pepperoni" />
<input type="checkbox" class="topping" value="Chilli" />
<input type="checkbox" class="topping" value="Cheese" />
<input type="checkbox" class="topping" value="Onion" />
<input type="checkbox" class="topping" value="Pepper" />
<button>Check</button>
推荐阅读
- arrays - 使用 Actionscript 3 的字节数组
- python - spyder 没有正确运行 kivy 脚本,但 IDLE 可以
- redash - Redash:从其他实例导入查询
- java - 是否有任何 java 插件可以自动使用 getter setter(如果提供)而不是 object.field?
- python - 使用python和通配符在目录中查找文件
- r - 在 R 中绘制宾夕法尼亚县的热图
- geb - 在 Geb 中指定多个环境
- django - Django:不支持的操作数类型 - :'NoneType'和'NoneType'
- google-sheets - 具有多个条件的 ARRAYFORMULA 总和
- python - 遍历字符串列表并替换某些字符