-1

我有一个表单验证器脚本,用于验证是否至少选中了 1 个复选框。

<form name="samples" onsubmit="return validateForm();" action="process.php" method="post">
    <input type="checkbox" name="products[]" value="product-a">
    <input type="checkbox" name="products[]" value="product-b">
    <input type="checkbox" name="products[]" value="product-c">
</form>

<script>
function validateForm() {
    var counter = document.forms["samples"]["products"].value;
    if (x == null || x == "") {
        alert("Please select at least one product");
        return false;
    }
}
</script>

上面的代码似乎不起作用。

我究竟做错了什么?

4

2 回答 2

1

您没有带有 name 的输入元素products,您确实有带有 name 的元素products[]

arrayOfProductInputs = document.forms["samples"]["products[]"];
// ^^^ loop through those

总共:

function validateCheckboxes()  {
    var arrayOfProductInputs = document.forms["samples"]["products[]"];
    var productsChecked = 0;
    arrayOfProductInputs.forEach(function(itm){
        if(itm.checked) productsChecked++;
    });

    if(productsChecked <= 0)  {
        alert("Please select at least one product");
        return false;
    }
    return true;
}
于 2013-08-22T19:12:51.717 回答
0
<script type = "text/javascript">
function validateForm() {
var flag = false;
var products = document.samples["products[]"];
for (var i = 0; i<products.length; i++) {
    if(products[i].checked){
        flag = true;
    }
}
if (flag != true) {
    alert("Please select at least one product");
    return false;
}
return true;
}
</script>
于 2013-08-22T19:15:35.120 回答