复选框验证器 [英] Checkbox validator
问题描述
我有一个复选框列表,我想确保用户在提交表单之前至少检查一个复选框。
这里有3个类别,每个类别有10个项目,我想在javascript中这样做,其中我将有一个隐藏的变量,然后当用户将检查任何复选框,隐藏的变量将有1作为其值,那么如果用户将取消选中该框,隐藏的变量将有0
如何标记它们?
我希望这样...
< input type =checkboxname =something []value = 55/>
然后在 PHP ...
if(!isset($ _ POST ['something'])或空($ _ POST ['something'])){
echo'复选框,请!
}
您也可以使用 JavaScript ...
var inputs = document.getElementById('my-form')。getElementsByTagName('input');
var checked = 0;
for(var i = 0,length = inputs.length; i if(inputs [i] .getAttribute('type')!=='checkbox'){
continue;
}
如果(inputs [i] .checked){
checked ++;
}
}
if(checked === 0){
alert('Select a checkbox,please!');
}
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.
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!');
}
这篇关于复选框验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!