首页 > 解决方案 > 获取选中的复选框

问题描述

该代码假设将浇头中的物品分为肉和无肉。然后我计划获取我选择的所有配料的名称。我的问题是,当我执行 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);
});

谢谢

标签: javascript

解决方案


在这里,使用一个mapjoin

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>


推荐阅读