问题
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 under each category with a checkbox.
I'm thinking of doing this in javascript wherein I will have a hidden variable then when the user will check any of the checkboxes, the hidden variable will have 1 as its value then if the user will uncheck the box, the hidden variable will have 0 as its value.
回答1:
How are you marking them up?
I hope like this...
<input type="checkbox" name="something[]" value="55" />
Then in PHP...
if ( ! isset($_POST['something']) OR empty($_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.
来源:https://stackoverflow.com/questions/3956128/checkbox-validator