Javascript 验证至少一个在动态添加的字段上选中的复选框
如果要向现有表单动态添加表单字段,那么添加验证的最佳方法是什么 以这把小提琴为例:Javascript 验证至少一个在动态添加的字段上选中的复选框,javascript,jquery,validation,dynamic,Javascript,Jquery,Validation,Dynamic,如果要向现有表单动态添加表单字段,那么添加验证的最佳方法是什么 以这把小提琴为例: 1. 2. 3. 添加框 $(函数(){ var parentdiv=$(“#parent”); var m=$('#parent div.child').size()+1; $('#addbox')。在('单击',函数()上){ $('12 3')。附录(parentdiv); m++; 返回false; }); }); 在该表单上,我正在添加新的复选框组,并希望确保每个组中至少选中一个复选框(而不是所有组
1.
2.
3.
添加框
$(函数(){
var parentdiv=$(“#parent”);
var m=$('#parent div.child').size()+1;
$('#addbox')。在('单击',函数()上){
$('12 3')。附录(parentdiv);
m++;
返回false;
});
});
在该表单上,我正在添加新的复选框组,并希望确保每个组中至少选中一个复选框(而不是所有组中的一个复选框)。有人有聪明的方法吗?由于动态添加的字段,我所看到的一切都会变得非常复杂。在提交等验证时,复选框是否是动态的并不重要。因此,类似这样的内容将检查每个
是否至少选中一个复选框。child
:
$('form').on('submit', function(e) {
e.preventDefault();
var valid = true;
$('.child').each(function() {
if ( ! $('[type="checkbox"]:checked', this).length ) // no box checked
valid = false;
});
if (valid) {
this.submit();
}else{
alert('error');
}
});
如果要使用jQuery进行检查,可以使用`.each() 您可以在以下链接中找到有关此jQuery函数的更多信息:
以下是我的想法。基本上,您可以循环.child组并测试它们是否有处于选中状态的复选框
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});
$(".child").each(function(){
var $this = $(this);
var checked = $this.find("input:checked");
if( checked.lenght == 0 ) {
alert("This group is not valid");
}
});
$('#checkBoxes').on('click', function(){
var uncheckedgroups = new Array();
$('.child').each(function(childindex, childelement){
var checkFound = 0;
$('.child').each(function(index, element){
if($(element).is(':checked')){
checkFound = 1;
}
});
if(checkFound == 0){
uncheckedgroups.push(childindex);
}
});
if(uncheckedgroups.length > 0){
alert("the following groups have no checked checkbox: " +
uncheckedgroups.join(','));
}
});