2010-10-26 88 views
11

我在表单上动态拖拽和显示单选按钮问题(由jquery选项卡分成不同的部分)。检查每个组中至少选择一个单选按钮(使用jquery)

所以有很多2,3,4,5等单选按钮放在一起,它们具有相同的“名称”但不同的ID。

当您在各个部分之间点击下一个时,我想检查是否为每个组选择了至少一个单选按钮。

(加载窗体时,单选按钮都没有默认选中的,它必须是这样。)

我可以遍历当前部分的单选按钮,但我不知道如何轻松地检查那一个已经被检查过每个组?

回答

21

在没有元素之间的任何关系或者如何找到组名的情况下,我只能给你一个指针,但是这个应该可以工作(点击id="nextButton"的元素触发检查,但显然这可以是定制以任何其他合适的事件,如$('form').submit(),例如):

$(document).ready(
function(){ 
    $('#nextButton').click(
    function(){ 

    var radioName = something; // use this if there's a relationship between the element 
           // triggering this check and the radio buttons 

     if ($('input[name='+ radioName +']:checked').length) { 
      // at least one of the radio buttons was checked 
      return true; // allow whatever action would normally happen to continue 
     } 
     else { 
      // no radio button was checked 
      return false; // stop whatever action would normally happen 
     } 
    } 
); 
} 
); 
3
$("input[@name='the_name']:checked").length; 
+2

自从jQuery 1.1.4(在评论部分)](http://api.jquery.com/attribute-equals-selector/),'@'语法已被弃用。 – 2010-10-26 22:57:50

2
if ($("input:checked").length < Num_of_groups) 
{ 
    alert ("Please select atleast one radio button in each group"); 
    return false; 
} 
0

尝试此

if ($('input[name='+radioName+']:checked').length == '0'){ 
    // do something 
    return false; 
} 
+2

这与接受的答案基本相同,只是更糟。你为什么要比较'数字'字段和'字符串'字面值? – meskobalazs 2015-02-16 10:53:20

相关问题