使用Javascript复选框出现问题

3

您好,我在获取复选框数值时遇到了问题。为了完成一个学校项目,我制作了一个披萨订购表格,现在需要打印订单汇总,但是无法正确打印配料信息。

<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还比较新,所以如果我犯了一个愚蠢的错误,请不要批评我。非常感谢。


输入集合数组的值是什么? - Kurt Spindler
这段JS代码看起来对我来说应该是可以工作的,但是我认为为了让它真正起作用,您需要通过将它们的“name”属性设置为“toppings []”来将topping-inputs变成一个数组。由于它们现在都被命名为“topping”,因此只有最后一个(?)会被发送到服务器。不确定这是否对JS有所帮助。 - powerbuoy
@powerbuoy:如果表单提交到 PHP,那么“[]”后缀约定只是必需的。这是 PHP 的限制;浏览器、Javascript 和大多数服务器都不在乎。 - Josh
2个回答

1
你是如何调用你的函数的?
这应该可以 - toppings(document.getElementsByName("topping"))

我已经想通了。我将它分配给了一个同名的变量toppings。谢谢。 - CodyK

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接