Javascript复选框的问题

Issues With Javascript Checkboxes

本文关键字:问题 复选框 Javascript      更新时间:2023-09-26

嗨,我在获取复选框值时遇到了一些问题。对于一个学校项目,我有一份披萨订单表,我想打印一份订单摘要。我在打印浇头时遇到问题。

<label><input type = "checkbox" name = "topping" id = "sausage" value = "Sausage"/>  Sausage</label>
<label><input type = "checkbox" name = "topping" id = "pepperoni" value = "Pepperoni"/>  Pepperoni</label>
<label><input type = "checkbox" name = "topping" id = "beef" value = "Beef"/>  Beef</label>
<label><input type = "checkbox" name = "topping" id = "bacon" value = "Bacon"/>  Bacon</label><br />
<label><input type = "checkbox" name = "topping" id = "chicken" value = "Chicken"/>  Chicken</label>
<label><input type = "checkbox" name = "topping" id = "ham" value = "Ham"/>  Ham</label>
<label><input type = "checkbox" name = "topping" id = "olives" value = "Olives"/>  Olives</label>
<label><input type = "checkbox" name = "topping" id = "peppers" value = "Peppers"/>  Peppers</label><br />
<label><input type = "checkbox" name = "topping" id = "tomatoes" value = "Tomatoes"/>  Tomatoes</label>
<label><input type = "checkbox" name = "topping" id = "mushrooms" value = "Mushrooms"/>  Mushrooms</label>
<label><input type = "checkbox" name = "topping" id = "pineapple" value = "Pineapple"/>  Pineapple</label>

这是html部分,我有我认为问题所在的javascript函数。

function toppings(inputCollection) {
    var toppings = "";
    for (var i = 0; i < inputCollection.length; i++) {
        if (inputCollection[i].checked) {
            toppings = toppings + inputCollection[i].value + " ";
        }
    }
    return toppings;
}

我是javascript的新手,所以如果我犯了一个愚蠢的错误,请不要激怒我。非常感谢

如何调用函数?

这应该做到——topings(document.getElementsByName("toping"))

看看这个例子,它还展示了如何正确使用标签:http://jsbin.com/upeqam