我有一个表单验证程序脚本,用于验证是否选中了至少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>
上面的代码似乎不起作用。
我做错了什么?
答案 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>