-1

I have a form validator script that is meant to verify that at least 1 checkbox is checked.

<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>

The code above does not seem to work.

What am I doing wrong?

Naftali
  • 144,921
  • 39
  • 244
  • 303
Brian Barrus
  • 385
  • 3
  • 6
  • 17

2 Answers2

1

You have no input element with name products, you do have elements with name products[]

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

In total:

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;
}
Naftali
  • 144,921
  • 39
  • 244
  • 303
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>
Ahsan Shah
  • 3,931
  • 1
  • 34
  • 48