Checkbox validator

蓝咒 提交于 2019-12-24 10:57:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!