Javascript检查数组是否已设置

时间:2013-08-22 19:08:23

标签: javascript forms validation

我有一个表单验证程序脚本,用于验证是否选中了至少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>

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您没有名称为products的输入元素,执行的元素名称为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;
}

答案 1 :(得分: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>