Tomps Tomps - 1 year ago 72
HTML Question

How can I validate more than one checkbox on submission?

I have two sets of checkboxes, named pizzaBase and pizzaTopping. I want to validate my form so that on submission at-least 1 base and topping must be selected.

function main() {
var form = document.getElementById('formname');
form.addEventListener('submit', validate);

function validate(event) {
var form = document.getElementById('formname');
if(!form.pizzaBase.checked) {
alert("select a base");
else if(!form.pizzaTopping.checked) {
alert("select topping");
else {
return true;


  1. Only first if statement works.

  2. Form submits true if checkbox is checked and then unchecked before

  3. Doesn't validate, doesn't work.

Where am I going wrong?

Thank you GG for pointing out JS is working, I have HTML below if someone wouldn't mind correcting me. I basically have two identical versions of the below code, one for bases and the other toppings.




<h2> Bases </h2>
<p><input type="checkbox" name="pizzaBase" data-price="1.00" data-human-desc = "Small" value="Small"> Small (£1.00) </p>
<p><input type="checkbox" name="pizzaBase"data-price="1.50" data-human-desc = "Medium" value="Medium"> Medium (£1.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="2.50" data-human-desc = "Large"value="Large"> Large (£2.50) </p>
<p><input type="checkbox" name="pizzaBase" data-price="3.50" data-human-desc = "XLarge"value="XLarge"> XLarge (£3.50) </p>

Not sure if I should ask a separate question here, but this is my messy HTML. Is it the sections? I was trying to split each set of check boxes (bases, toppings) into two separate sections so used this tag.

Any ideas?

Answer Source

When you have multiple inputs with the same name, form.elementName will be an array-like list of elements.

The list won't have a checked property. Each item within it will.

You need to loop over the list and check to see if any of the elements are checked.

function areAnyChecked(list) {
    for (var i = 0; i < list.length; i++) {
        if (list[i].checked) { 
            return true;
    return false;

if(! areAnyChecked(form.pizzaBase)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download