jquery:如何检查是否选中了div中的所有单选按钮

我的HTML看起来像这样

单选按钮是在我的html上动态生成的,所以在div中我不知道我有多少单选按钮。

我想确保用户在提交表单之前为每一个选择一个值,如何检查我的div中的所有单选按钮是否都检查了值?

谢谢

稍微重构您的HTML – 将每个广播组包装在(例如)div中。 然后你可以做这样的事情来在用户提交时validation表单:

 if ($('div:not(:has(:radio:checked))').length) { alert("At least one group is blank"); } 

当然,可以通过各种方式调整以适应您的HTML。 这个想法来自查找尚未被选中的所有无线电组

 $(":radio").change(function() { var names = {}; $(':radio').each(function() { names[$(this).attr('name')] = true; }); var count = 0; $.each(names, function() { count++; }); if ($(':radio:checked').length === count) { alert("all answered"); } }).change(); 

演示: http : //jsfiddle.net/yFaAj/15/

解决方案 http://jsfiddle.net/QxdnZ/1/

  var checked = $("#div1 :radio:checked"); var groups = []; $("#div1 :radio").each(function() { if (groups.indexOf(this.name) < 0) { groups.push(this.name); } }); if (groups.length == checked.length) { alert('all are checked!'); } else { var total = groups.length - checked.length; var a = total>1?' groups are ':' group is '; alert(total + a + 'not selected'); } 

使用此validation代码在用户提交表单时validation表单。

 var blank = false; $("input:radio").each(function() { var val = $('input:radio[name=' + this.name + ']:checked').val(); if (val === undefined) { blank = true; return false; } }); alert(blank ? "At least one group is blank" : "All groups are checked"); 

首先,我们获取所有单选按钮组的名称,然后检查每个单选按钮组是否有值。 (实际上我们正在做多次检查,但这并不重要。)

试试这个:

 $('input:radio', $('#div1')).each(function() { if(name && name == $(this).attr('name')) return true; // Skip when checking the same element name. name = $(this).attr('name'); if(! $('input:radio[name="' + name + '"]:checked').length) { alert('Oops, you missed some input there.. [' + name + ']'); return false; } }); 

它将遍历每个单选按钮以检查已检查的无线电,并在找到未检查的无线电组后立即中断(发现第一个错误)。 但是,如果您希望获得所有错误(不仅是找到的第一个错误),只需删除return false

试试这个:

 function check(){ var allCheck = true; if($("#div1 :radio:checked").length==0){ allCheck=false; } $("#div1 :radio").each(function(){ for(var i=0;i<$("#div1 :radio:checked").length;i++) if($(this).attr("name")===$($("#div1 :radio:checked")[i]).attr("name")) break; else if(i==$("#div1 :radio:checked").length-1) allCheck = false; }); return allCheck; } 

这将有效:

 if($("#div1").children("input:radio:checked").size() == 3) { alert('three inputs were checked'); } 

在这些方面寻找一些东西? http://jsfiddle.net/gXsZp/3/

 
Q1
Q2
Q3

$('#btn').click(function(){ if ( $('#div1 input:radio:checked').size() == 3 ) return true; return false; });