Skip to content Skip to sidebar Skip to footer

Checkbox Validator

I have a list of checkboxes and I would want to make sure that the user will check at least one before submitting the form. How can I do this? There are 3 categories then 10 items

Solution 1:

How are you marking them up?

I hope like this...

<inputtype="checkbox" name="something[]" value="55" />

Then in PHP...

if ( ! isset($_POST['something']) ORempty($_POST['something'])) {
   echo'Select a checkbox, please!';
}

You can also check with JavaScript...

var inputs = document.getElementById('my-form').getElementsByTagName('input');
var checked = 0;
for (var i = 0, length = inputs.length; i < length; i++) {
    if (inputs[i].getAttribute('type') !== 'checkbox') {
       continue;
    }

    if (inputs[i].checked) {
        checked++;
    }
}

if (checked === 0) {
   alert('Select a checkbox, please!');
}

See it working on JSbin.

Post a Comment for "Checkbox Validator"