jQuery中的动态单选按钮组validation

validation以确保每个组中至少有一个被检查的最佳方法是什么,因此在以下示例中,组是name1name2name3

          

我知道我可以围绕每个div包装div然后检查div中的每个单选按钮,但我正在寻找一个更动态的解决方案。 因此,如果将来添加更多单选按钮,则不需要更改jQuery代码或不需要添加div – 我希望这是有道理的。

您应该使用jquery.validate.js库来帮助您解决这个问题,看看他们的演示

如果您使用该库,它将如此简单,

       

查看jFiddle :这会找到单选按钮的所有不同名称,然后运行所有这些不同的组,并确保至少有一个已检查,如果不是,它将发出警报。

 $('#button').click(function() { var names = []; $('input[type="radio"]').each(function() { // Creates an array with the names of all the different checkbox group. names[$(this).attr('name')] = true; }); // Goes through all the names and make sure there's at least one checked. for (name in names) { var radio_buttons = $("input[name='" + name + "']"); if (radio_buttons.filter(':checked').length == 0) { alert('none checked in ' + name); } else { // If you need to use the result you can do so without // another (costly) jQuery selector call: var val = radio_buttons.val(); } } }); 
 $('[name="name1"]:checked').length != 0 

要么

 $('[name="name1"]').is(':checked') 

如果你愿意,你也可以做一些更有活力的事情:

 var i = 1; while ($('[name="name'+i+'"]').length != 0) { if ($('[name="name'+i+'"]').is(':checked')) { // at least one is checked in this group } else { // none are checked } i++; }